ZOJ

来源:互联网 发布:淘宝联盟 鹊桥 编辑:程序博客网 时间:2024/05/21 06:28

Numbers

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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

53 13 23 310000 51244 10

Sample Output

3312000125


题意:将一个数n拆分为m个数之和,求这m个数进行或操作后的最小值


或操作: 1 | 1 = 1 ; 1 | 0 = 0 ; 0 | 0 = 0 ;


从前往后进行操作

判断该位(第k位)是否一定要为1,若一定要为1则尽量多分,最多分m个

即最多分 1<<(k-1) * m,令其为p,若 n - p < 0 则 n = n % (1<<(k-1)),若  n - p >= 0 则 n = n - p

若可以不分则继续判断下一位直到最后一位或n = 0


判断是否必须要放1的标准就是 判断 ( ( 1<<(k-1) ) - 1 ) * m 与 n 的关系,就是后面所有位的数都是1的情况是否能将剩下的 n 用完,不能用完则一定要为1 ,否则为 0


用Java 来写大数十分的方便


import java.math.BigInteger;import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner cin = new Scanner(System.in);BigInteger[] a = new BigInteger [4000];BigInteger now = BigInteger.ONE;BigInteger big = BigInteger.valueOf(10).pow(1000);for(int i=0;;i++){a[i] = now;now = now.add(now);if(now.compareTo(big)==1){break;}}int T;while(cin.hasNext()){T = cin.nextInt();while(T > 0) {T--;String N,M;N = cin.next();M = cin.next();BigInteger n = new BigInteger(N);BigInteger m = new BigInteger(M);int l = 0,r = 3321,mid = 0;while(l < r){mid = (l+r) / 2;if(a[mid].compareTo(n)==-1) l = mid + 1;else if(a[mid].compareTo(n)==1) r = mid - 1;else { l = mid; break;}}BigInteger ans = BigInteger.ZERO;for(int i=l;i>=0;i--) {if(n.equals(BigInteger.ZERO)) break;BigInteger sum = (a[i].subtract(BigInteger.ONE)).multiply(m);if(sum.compareTo(n)==-1){ans = ans.add(a[i]);if(a[i].multiply(m).compareTo(n)==1){n = n.remainder(a[i]);} else {n = n.subtract(a[i].multiply(m));}}else if(sum.equals(n)){ans = ans.add(a[i].subtract(BigInteger.ONE));break;}}System.out.println(ans);}}cin.close();}}


原创粉丝点击