您的位置:首页 > 其它

ZOJ - 3987 - Numbers (高精度,贪心)

2017-12-19 15:59 447 查看
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

5
3 1
3 2
3 3
10000 5
1244 10

Sample Output

3
3
1
2000
125


题意:将一个数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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: