标签:必须 分析 大数 mat [] math VID 最小 代码
题意:
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);
}
}
}
标签:必须 分析 大数 mat [] math VID 最小 代码
原文地址:https://www.cnblogs.com/ccut-ry/p/9052595.html