HackerRank - Bricks Game
2015-03-25 06:24
253 查看
One sentence in the problem statement is crucial "your friend will also play optimally", if you interpret it correctly, you are very close to AC. What does it mean? It means, no matter what your current choice is, 1 brick or 2 or 3, your opponent will take optimized score of the rest bricks. Then, it is natural to have a 'reverse' DP:
(thanks to http://massivealgorithms.blogspot.com/2015/01/hackerrank-play-game.html)
(thanks to http://massivealgorithms.blogspot.com/2015/01/hackerrank-play-game.html)
t = int(input()) for i in range(t): n = int(input()) arr = [int(i) for i in input().strip().split()] ###### def calc(arr): alen = len(arr) if alen < 4: return sum(arr) ''' Both DP[] and PreSum[] is in terms of bottom-up because opponent 'your friend will also play optimally' ''' # Calc prefix sum presum = [0] * alen presum[0] = arr[0] for i in range(1, alen): presum[i] = presum[i - 1] + arr[i] # Go DP dp = [0] * (alen) dp[0] = arr[0] dp[1] = arr[1] + dp[0] dp[2] = arr[2] + dp[1] for i in range(3, alen): # Take 1: (i), opponent will take dp[i - 1] x = arr[i] + presum[i - 1] - dp[i - 1] # Take 2 y = presum[i - 2] + arr[i] + arr[i - 1] - dp[i - 2] # Take 3 z = presum[i - 3] + arr[i] + arr[i - 1] + arr[i - 2] - dp[i - 3] dp[i] = max(x, y, z) return dp[alen - 1] ###### # reverse to bottom -> top arr.reverse() print (calc(arr))
相关文章推荐
- 【Hackerrank】Get the value of the node at a specific position from the tail
- HackerRank - "Sherlock and GCD"
- HackerRank - "Sherlock and MiniMax"
- Hackerrank,set、list时间复杂度问读
- HackerRank-Left Rotation
- HackerRank初级篇之Between Two Sets
- hackerrank: Insertion Sort Advanced Analysis
- HackerRank - Even Tree
- HackerRank - "Detecting Valid Latitude and Longitude Pairs"
- Hackerrank :Candies
- HackerRank-Hash Tables: Ransom Note
- HackerRank - camelcase 【字符串】
- Hackerrank 2020 February 2014 解题报告
- HackerRank - Cut the Tree
- HackerRank - "Building a Smart IDE: Identifying comments"
- HackerRank Largest Rectangle
- HackerRank-Tree: Level Order Traversal
- HackerRank - angry-children 【排序】
- Hackerrank - Game Of Rotation 题解
- HackerRank - Count Luck