Numbers(模擬)

ZOJ - 3987

DreamGrid has a nonnegative integer n. He would like to divide n into m nonnegative integers a1,a2,,ama_1, a_2, \dots, a_m​ and minimizes their bitwise or (i.e. n=a1+a2++amn=a_1 + a_2 + \dots + a_m​ and a1 OR a2 OR  OR ama_1 \text{ OR } a_2 \text{ OR } \dots \text{ OR } a_m​ 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 (0n<101000,1m<101000 \le n < 10^{1000}, 1 \le m < 10^{100}).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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章