Stop learning useless algorithms, go and solve some problems, learn how to use binary search.
注意到如果分出胜负,一定存在一个时刻恰有一方的棋子数量 ,且通过这个时刻就能得知获胜的一方。
二分查找即可。如果此时双方棋子数量都 则继续二分后面的区域,如果此时双方棋子数量都 则继续二分前面的区域。
n, M = map(int, input().split())
a = [int(input()) for _ in range(n)]
def ans(l, r):
if l > r:
return "Draw"
mid = (l + r) // 2
W = sum(a[i] for i in range(0, mid+1, 2)) > M
B = sum(a[i] for i in range(1, mid+1, 2)) > M
if W and not B:
return "White"
if B and not W:
return "Black"
if B and W:
return ans(l, mid-1)
if not B and not W:
return ans(mid+1, r)
print(ans(0, n-1))最坏时间复杂度 ,目前位于最优解第一页。