標籤:16px 計算 main com out 答案 class ann rgs
目錄
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); }}
演算法筆記168:曆屆試題 矩陣翻硬幣(Java)