2016 CCPC 秦皇岛 G Numbers 【贪心+大数+高精度】

来源:互联网 发布:淘宝买的lol号安全吗 编辑:程序博客网 时间:2024/05/17 01:48

题目链接:ZOJ 3987 Numbers

Problem Description

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).

Input

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 < 10^1000,1 ≤ m < 10^100).

It is guaranteed that the sum of the length of does not exceed 20000.

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个非负数的和,要求这些数的逻辑或后的值最小,输出这个最小的值。

解题思路:

Mycode

import java.util.*;import java.math.*;public class Main{    static BigInteger bit[] = new BigInteger [4005];    static BigInteger one = BigInteger.ONE;    static BigInteger two = BigInteger.valueOf(2);    static BigInteger zero = BigInteger.ZERO;    static BigInteger n, m;    public static void Init()    {        bit[0] = one;        for(int i = 1; i <= 4000; ++i)        {            bit[i] = bit[i-1].multiply(two);        }    }    public static void Work()    {        BigInteger sum = zero, tmp = n, ans = zero;        int up = 0;        for(int i = 0; sum.compareTo(n) < 0; ++i)        {            sum = sum.add(m.multiply(bit[i]));            up = i;        }        for(int i = up; i >= 0; --i)        {            BigInteger t = bit[i].subtract(one);            if(t.multiply(m).compareTo(tmp) >= 0) continue;            BigInteger k = tmp.divide(bit[i]);            k = k.min(m);            tmp = tmp.subtract(bit[i].multiply(k));            ans = ans.add(bit[i]);        }        System.out.println(ans);    }    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        Init();        int t = sc.nextInt();        for(int i = 1; i <= t; ++i)        {            n = sc.nextBigInteger();            m = sc.nextBigInteger();            Work();        }    }}