蓝桥杯 矩阵翻硬币(打表+二分)

网上其他人的答案好像都是用数学方法解决的。

做这道题的时候一看就感觉是找规律的题,所以先打个表。

因为后面要用到大数处理,所以是Java语言

打表代码(就是按题目意思暴力):

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;


public class daBiao {

	/**
	 * @param args
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) throws FileNotFoundException {
		// TODO Auto-generated method stub
		FileOutputStream fos=new FileOutputStream("out.txt");
		PrintStream ps=new PrintStream(fos);
		System.setOut(ps);
		int m,n;
		int i,j;
		for(m=1;m<100;m++)
			for(n=1;n<100;n++){
				int a[][]=new int[m+1][n+1];
				for(i=0;i<m+1;i++)
					for(j=0;j<n+1;j++)
						a[i][j]=1;
				int k=fun(a,m,n);
				System.out.println(m+" "+n+" "+k);
			}
	}
	
	public static int fun(int a[][],int m,int n){
		int count=0;
		for(int x=1;x<=m;x++)
			for(int y=1;y<=n;y++){
				for(int i=1;i*x<=m;i++)
					for(int j=1;j*y<=n;j++){
						if(i*x<=m&&j*y<=n)
						a[i*x][j*y]=a[i*x][j*y]^1;
					}
			}
		for(int i=1;i<m+1;i++)
			for(int j=1;j<n+1;j++){
				if(a[i][j]==0)
					count++;
			}
		return count;
	}
	
	

}

当然这里打表用C语言也可以 枚举了10000组数据之后能很明显的发现规律,最后要输出的答案就是sqrt(m)*sqrt(n)。(向下取整)

下面要解决的就是大数的问题了

我这里用的是二分Java大数

import java.math.BigInteger;
import java.util.Scanner;


public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BigInteger n,m;
		Scanner sc=new Scanner(System.in);
		n=sc.nextBigInteger();
		m=sc.nextBigInteger();
		n=bsqrt(n);
		m=bsqrt(m);
		n=n.multiply(m);
		System.out.println(n);
		
	}
	
	public static BigInteger bsqrt(BigInteger i){
		BigInteger one=new BigInteger("1");
		BigInteger two=new BigInteger("2");
		BigInteger low=new BigInteger("0");
		BigInteger high=i.add(one);
		BigInteger k=i;
		while(low.compareTo(high)<0){
			if(low.equals(high.subtract(BigInteger.ONE))) break;		
			k=high.add(low).divide(two);
			if(k.multiply(k)==i) return k;
			else if((k.multiply(k)).compareTo(i)>0) high=k;
			else low=k;
		}
		
		return low;
	}

}

最后提交的代码也就二十多行

成功通过官网所有数据^_^

猜你喜欢

转载自blog.csdn.net/zyw764662004/article/details/79368487