zoukankan      html  css  js  c++  java
  • 算法笔记_168:历届试题 矩阵翻硬币(Java)

    目录

    1 问题描述

    2 解决方案

     


    1 问题描述

    问题描述
      小明先把硬币摆成了一个 n 行 m 列的矩阵。

      随后,小明对每一个硬币分别进行一次 Q 操作。

      对第x行第y列的硬币进行 Q 操作的定义:将所有第 i*x 行,第 j*y 列的硬币进行翻转。

      其中i和j为任意使操作可行的正整数,行号和列号都是从1开始。

      当小明对所有硬币都进行了一次 Q 操作后,他发现了一个奇迹——所有硬币均为正面朝上。

      小明想知道最开始有多少枚硬币是反面朝上的。于是,他向他的好朋友小M寻求帮助。

      聪明的小M告诉小明,只需要对所有硬币再进行一次Q操作,即可恢复到最开始的状态。然而小明很懒,不愿意照做。于是小明希望你给出他更好的方法。帮他计算出答案。
    输入格式
      输入数据包含一行,两个正整数 n m,含义见题目描述。
    输出格式
      输出一个正整数,表示最开始有多少枚硬币是反面朝上的。
    样例输入
    2 3
    样例输出
    1
    数据规模和约定
      对于10%的数据,n、m <= 10^3;
      对于20%的数据,n、m <= 10^7;
      对于40%的数据,n、m <= 10^15;
      对于10%的数据,n、m <= 10^1000(10的1000次方)。

    2 解决方案

    具体代码如下:

    import java.math.BigInteger;
    import java.util.Scanner;
    
    public class Main {
        
        public static BigInteger getSqrt(String A) {
            String sqrt = "0";
            String pre = "0";
            BigInteger twenty = new BigInteger("20");
            BigInteger temp1 = BigInteger.ZERO;
            BigInteger temp2 = BigInteger.ZERO;
            int len = A.length();
            if(len % 2 == 1) {
                A = "0" + A;
                len = len + 1;
            }
            for(int i = 0;i < len / 2;i++) {
                BigInteger tempN = new BigInteger(pre + A.substring(i*2, i*2 + 2));
                for(int j = 0;j <= 9;j++) {
                    BigInteger tempJ = new BigInteger(j+"");
                    temp1 = twenty.multiply(new BigInteger(sqrt)).add(tempJ).multiply(tempJ);
                    tempJ = tempJ.add(BigInteger.ONE);
                    temp2 = twenty.multiply(new BigInteger(sqrt)).add(tempJ).multiply(tempJ);    
                    if(temp1.compareTo(tempN) <= 0 && temp2.compareTo(tempN) > 0) {
                        sqrt = sqrt + j;
                        pre = tempN.subtract(temp1).toString();
                        break;
                    }
                }
            }
            return new BigInteger(sqrt);
        }
        
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            String n = in.next();
            String m = in.next();
            BigInteger result = getSqrt(n).multiply(getSqrt(m));
            System.out.println(result);
        }
    }
  • 相关阅读:
    Google's Innovation Factory (and how testing adapts)
    虎年拜年帖
    [ZZ]让测试也敏捷起来
    Selenimu做爬虫续
    OKR的解说
    春秋航空的机上店铺
    免费TK域名试用
    快速排序_C语言实现
    第一篇博客
    C、C++代码格式优化软件献给编程爱好者
  • 原文地址:https://www.cnblogs.com/liuzhen1995/p/6797549.html
Copyright © 2011-2022 走看看