DreamGrid has a nonnegative integer . He would like to divide into nonnegative integers and minimizes their bitwise or (i.e. and should be as small as possible).
Input
There are multiple test cases. The first line of input contains an integer , indicating the number of test cases. For each test case:
The first line contains two integers and ().
It is guaranteed that the sum of the length of does not exceed .
Output
For each test case, output an integer denoting the minimum value of their bitwise or.
Sample Input
5 3 1 3 2 3 3 10000 5 1244 10
Sample Output
3 3 1 2000 125
Author: LIN, Xi
Source: The 2017 China Collegiate Programming Contest, Qinhuangdao Site
POINT:
第一次用java写大数,好方便啊!
这题简单的贪心就行了。
从高位开始判断,判断这一位的0可以不可以给:
可以给的状态是 假设这一位后面的数全是1111,这1111*m不小于当前要填满的n,那么这个0就可以放。
import java.math.BigInteger;
import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int T;
while(cin.hasNext()){
T=cin.nextInt();
while(T!=0) {
BigInteger n = cin.nextBigInteger();
BigInteger m = cin.nextBigInteger();
BigInteger now = BigInteger.valueOf (1);
BigInteger er =BigInteger.valueOf(2);
BigInteger sum = m.multiply(now);
int k=1;
while(sum.compareTo(n)==-1) {
k++;
now=now.multiply(er);
sum=sum.add(now.multiply(m));
}
BigInteger ans = BigInteger.ZERO;
// System.out.println(now);
while(n.compareTo(BigInteger.ZERO)!=0) {
BigInteger num = n.divide(now);
if(num.compareTo(m)==1) {
num=m;
}
BigInteger now1 = now.subtract(BigInteger.ONE);
if(now1.multiply(m).compareTo(n)!=-1) {
now=now.divide(er);
continue;
}
ans=ans.add(now);
n=n.subtract(num.multiply(now));
now=now.divide(er);
}
System.out.println(ans);
T--;
}
}
}
}