时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 65536K,其他语言131072K
64bit IO Format: %lld
空间限制:C/C++ 65536K,其他语言131072K
64bit IO Format: %lld
题目描述
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).
输入描述:
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 n the length of does not exceed 20000.
输出描述:
For each test case, output an integer denoting the minimum value of their bitwise or.
示例1
输入
5 3 1 3 2 3 3 10000 5 1244 10
输出
3 3 1 2000 125
java 太麻烦了,,上py了。。题意:
给一个数n和一个数m,让你将n这个数分成m个数(相加为n),且这m个数的or值最小。输出该或值。(n <= 1e1000, m <= 1e100)
思路:
由于让我们输出最小的或值,那么我们不必关心分的过程,直接去构造这个或值就好。因为要求分成m份,我们可以看成n是由m个不同二进制位1组成的。所以首先通过sum不断的从0位向高位加m*2^k次方,直到sum大于等于n停止,然后就可以开始从这个位向低位去构造。对于当前位k,由于是从高位到低位,所以我们肯定更不想选择较高位的1,更想让较低位的1来贡献给n这个数,所以如果从k-1位到0位所有的位都选择m个都不能构造出大于当前n所需要贡献的剩余数值,那么表示必然要选择若干个这第k位的1,而由于我们最终要求得或值,既然必须得用这第k位的贡献,那么我们就让它贡献尽可能多的贡献,从而减少后续所需的贡献。依此贪心下去,必定能构造出n,从而也能求出最终的或值。
import math
t = int(input())
for i in range(t):
n, m = map(int, input().split())
y = 1
while y < n:
y *= 2
ans = 0
while n:
#print(str(n) + " " + str(y))
if (y - 1) * m >= n:
y //= 2
continue
ans += y
n -= y * min(m, n // y)
y //= 2
print(ans)