2017 CCPC 秦皇岛 & ZOJ 3987 - Numbers (贪心+大数)

本文介绍了一种使用Java处理大数的贪心算法方法,该方法应用于解决将一个非负整数拆分为多个非负整数的问题,并最小化这些整数的按位或运算结果。文章通过一个具体的竞赛题目来展示算法实现细节。
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

Author: LIN, Xi
Source: The 2017 China Collegiate Programming Contest, Qinhuangdao Site


POINT:
第一次用java写大数,好方便啊!
这题简单的贪心就行了。
从高位开始判断,判断这一位的0可以不可以给:
可以给的状态是 假设这一位后面的数全是1111,这1111*m不小于当前要填满的n,那么这个0就可以放。

import java.math.BigInteger;
import java.util.Scanner;
import java.math.*;


public class Main {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);  
		int T;
		while(cin.hasNext()){  
			T=cin.nextInt();
			while(T!=0) {
				BigInteger n = cin.nextBigInteger();
				BigInteger m = cin.nextBigInteger();
				BigInteger now = BigInteger.valueOf (1);
				BigInteger er =BigInteger.valueOf(2);
				BigInteger sum = m.multiply(now);
				int k=1;
				while(sum.compareTo(n)==-1) {
					k++;
					now=now.multiply(er);
					sum=sum.add(now.multiply(m));
				}
				BigInteger ans = BigInteger.ZERO;
			//	System.out.println(now);
				while(n.compareTo(BigInteger.ZERO)!=0) {
					BigInteger num = n.divide(now);
					if(num.compareTo(m)==1) {
						num=m;
					}
					BigInteger now1 = now.subtract(BigInteger.ONE);
					if(now1.multiply(m).compareTo(n)!=-1) {
						now=now.divide(er);
						continue;
						
					}
					ans=ans.add(now);
					n=n.subtract(num.multiply(now));
					now=now.divide(er);
				}
				System.out.println(ans);
				T--;
			}
        }
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值