DreamGrid has a nonnegative integer n. He would like to divide n into m nonnegative integers a 1 , a 2 , … , a m a_1, a_2, \dots, a_m a1,a2,…,am and minimizes their bitwise or (i.e. n = a 1 + a 2 + ⋯ + a m n=a_1 + a_2 + \dots + a_m n=a1+a2+⋯+am and a 1 OR a 2 OR … OR a m a_1 \text{ OR } a_2 \text{ OR } \dots \text{ OR } a_m 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 < 1 0 1000 , 1 ≤ m < 1 0 100 0 \le n < 10^{1000}, 1 \le m < 10^{100} 0≤n<101000,1≤m<10100).It is guaranteed that the sum of the length of nnn 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
让高位最小然后向低位贪心,判断当前为能否为0,能为0的条件是后面几位都是1,并且有m个,加起来如果大于当前值的话那么这位就可以为0,否则只能为1,既然为1了,那么尽量多填1,这样保证了结果最优。
#Copy From 907
T = int(input())
for t in range(T):
n,m = [int(x) for x in input().split()]
ans,p = int(0),int(1)
while((p - 1) * m < n):
p <<= 1
while(n != 0):
while((p-1) * m >= n):
p >>= 1
ans += p
if(p * m <= n):
n -= p * m
else:
n %= p
print(ans)
本文探讨了如何将一个非负整数n拆分为m个非负整数的和,同时使这些数的位或运算结果尽可能小。通过高位到低位的贪心策略,判断每位是否可以为0,若条件允许则设为0,否则设为1并填充尽可能多的1,以确保结果的最优性。
304

被折叠的 条评论
为什么被折叠?



