Day6_模拟人生
Day6_模拟人生
#!/usr/bin/env python # encoding: utf-8 def dist(n, g = 100): """all plans for n people, best first""" if n == 1: yield [g] return for i in range(g, -1, -1): for d in dist(n-1, g-i): yield [i] + d D = {} #memoization def solve(n): """return best plan""" if n in D: return D[n] for d in dist(n): #plan can be agreed by a majority if sum(vote(d,i) for i in range(n)) > n/2: D[n] = d return d D[n] = None return None #no plan to save my life def vote(d,i): """ith pirate's vote for plan d""" #vote 1 if the plan is mine if i == 0: return 1 #vote 1 if I'm gonna die n = len(d) while solve(n-1) == None: n -= 1 i -= 1 if i <= 0: return 1 #vote 0 if next pirate's plan is better if solve(n-1)[i-1] >= d[i]: return 0 #vote 1 if there's no better plan for me return 1 print (solve(1)) print (solve(2)) print (solve(3)) print (solve(4)) print (solve(5)) print (solve(6)) print (solve(7))
公众号请关注:侠之大者

浙公网安备 33010602011771号