JAVA大數貪心
阿新 • • 發佈:2018-05-17
args port 簡單 compare 一位 class big 題意 AI
題意:
01給出一個數n,現在要將它分為m個數,這m個數相加起來必須等於n,並且要使得這m個數的或值最小。
思路分析:
一個簡單的貪心,從高位到低位,判斷當前位可否為 1 ,若可以,則將所有的數的這一位全部都變成 1
代碼示例:
import java.math.*; import java.util.*; public class study { public static void main(String[] args) { Scanner cin = new Scanner(System.in); BigInteger n, m; int t = cin.nextInt(); for(int cas = 0; cas < t; cas++) { n = cin.nextBigInteger(); m = cin.nextBigInteger(); BigInteger ans = BigInteger.valueOf(0); int len = 0; BigInteger ss = n, v = BigInteger.valueOf(0); while(ss.compareTo(v)>0){ ss = ss.divide(BigInteger.valueOf(2)); len++; } for(int i = len; i >= 0; i--) { BigInteger tem = BigInteger.valueOf(2); tem = tem.pow(i).subtract(BigInteger.valueOf(1)).multiply(m); //System.out.println(tem); if (tem.compareTo(n) < 0) { BigInteger f = BigInteger.valueOf(2).pow(i); ans = ans.add(f); BigInteger p = n.divide(f); if (p.compareTo(m) >= 0) n = n.subtract(m.multiply(f)); else n = n.subtract(p.multiply(f)); //System.out.println(f); //System.out.println(p); } } System.out.println(ans); } } }
JAVA大數貪心