题目链接:传送门
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
解题思路:要想使或值最小,那么m个二进制数中的最高位应尽量小,假如存在k使(2^k-1)*m > n > (2^(k-1)*-1)*m,所以m个二进制数中至少有一个数的最高位为k。因为是取各位取或,所以此时应让尽量多的数的第k位为1,ans += 2^k,从高位向低位递推,直到n变为0。
import java.math.*;
import java.io.*;
import java.util.*;
public class Main{
public static BigInteger bin[] = new BigInteger[4500];
public static BigInteger tw = BigInteger.valueOf(2);
public static void init(){
bin[0] = BigInteger.ONE;
for( int i = 1 ; i < 4500 ; ++i ){
bin[i] = bin[i-1].multiply(tw);
}
}
public static BigInteger solve(BigInteger a,BigInteger b){
BigInteger re = BigInteger.ZERO;
int up = 0;
for( int i = 0 ; i < 4500 ; ++i ){
re = re.add(b.multiply(bin[i]));
up = i;
if(re.compareTo(a) >= 0) break;
}
//System.out.println(up);
BigInteger ans = BigInteger.ZERO;
for( int i = up ; i >= 0 ; --i ){
if(a.equals(BigInteger.ZERO)) break;
if(b.multiply(bin[i]).compareTo(a) > 0){
if(re.subtract(b.multiply(bin[i])).compareTo(a) >= 0){
re = re.subtract(b.multiply(bin[i]));
continue;
}
BigInteger t = a.divide(bin[i]);
a = a.subtract(t.multiply(bin[i]));
ans = ans.add(bin[i]);
}else{
a = a.subtract(b.multiply(bin[i]));
ans = ans.add(bin[i]);
}
re = re.subtract(b.multiply(bin[i]));
//System.out.println(ans);
}
return ans;
}
public static void main(String[]args){
init();
int T;
Scanner cin = new Scanner(System.in);
T = cin.nextInt();
for( int i = 0 ; i < T ; ++i ){
BigInteger a,b;
a = cin.nextBigInteger();
b = cin.nextBigInteger();
System.out.println(solve(a, b));
}
}
}