zoj3987—Numbers(贪心)

题目链接:传送门

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


解题思路:要想使或值最小,那么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));
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值