鏈接:https://ac.nowcoder.com/acm/problem/14371
來源:牛客網
DreamGrid has a nonnegative integer n, He would like to divide n into m nonnegative integers a1,a2,…am and minimizes their bitwise or (i.e:n = a1 + a2 + … + am and a1 OR a2 OR … OR am should be as small as possible).
輸入描述:
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains two integers n and m (0 ≤ n < 101000,1 ≤ m < 10100)
It is guaranteed that the sum of n the length of does not exceed 20000.
輸出描述:
For each test case, output an integer denoting the minimum value of their bitwise or.
示例1
輸入
複製
5
3 1
3 2
3 3
10000 5
1244 10
輸出
複製
3
3
1
2000
125
思路:其實也沒啥,就是大數類寫的會有點煩
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
while(T>0){
BigInteger n=sc.nextBigInteger();
BigInteger m=sc.nextBigInteger();
int len=0;
BigInteger tmp=n;
while(tmp.compareTo(BigInteger.ZERO)!=0){
tmp=tmp.shiftRight(1);
len++;
}
BigInteger ans=BigInteger.ZERO;
for(int i=len-1;i>=0 && n.compareTo(BigInteger.ZERO)>0;i--){
BigInteger cnt=BigInteger.ONE.shiftLeft(i);
tmp=cnt.subtract(BigInteger.ONE).multiply(m);
if(tmp.compareTo(n)< 0){
n=n.subtract(cnt.multiply(m.min(n.shiftRight(i))));
ans=ans.or(cnt);
}
}
System.out.println(ans);
T--;
}
sc.close();
}
}