Numbers(模拟)

本文探讨了如何将一个非负整数n拆分为m个非负整数的和,同时使这些数的位或运算结果尽可能小。通过高位到低位的贪心策略,判断每位是否可以为0,若条件允许则设为0,否则设为1并填充尽可能多的1,以确保结果的最优性。

ZOJ - 3987

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} 0n<101000,1m<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

#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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值