我正在嘗試解決這個 cp 問題,UVA - The Playboy Chimp using Python,但由于某種原因,對于非常大的值,例如這個輸入,答案是錯誤的:
5
3949 45969 294854 9848573 2147483647
5
10000 6 2147483647 4959 5949583
接受的輸出:
3949 45969
X 3949
9848573 X
3949 45969
294854 9848573
我的輸出:
X 294854
X 294854
9848573 X
X 294854
45969 9848573
我的代碼:
def bs(target, search_space):
l, r = 0, len(search_space) - 1
while l <= r:
m = (l r) >> 1
if target == search_space[m]:
return m - 1, m 1
elif target > search_space[m]:
l = m 1
else:
r = m - 1
return r, l
n = int(input())
f_heights = list(set([int(a) for a in input().split()]))
q = int(input())
heights = [int(b) for b in input().split()]
for h in heights:
a, b = bs(h, f_heights)
print(f_heights[a] if a >= 0 else 'X', f_heights[b] if b < len(f_heights) else 'X')
任何幫助,將不勝感激!
uj5u.com熱心網友回復:
這是因為您將第一個輸入插入到set,這會更改串列中數字的順序。如果您使用 Python 3.6 或更新版本來
dict維護插入順序,那么您可以使用dict.fromkeys來維護順序
f_heights = list(dict.fromkeys(int(a) for a in s.split()))
例子:
f_heights = list(set([int(a) for a in input().split()]))
print(f_heights) # [294854, 3949, 45969, 9848573, 2147483647]
f_heights = list(dict.fromkeys(int(a) for a in input().split()))
print(f_heights) # [3949, 45969, 294854, 9848573, 2147483647]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/475517.html
