【发布时间】:2020-07-16 07:53:01
【问题描述】:
一些公司提出的 SpaceKings 问题的解决方案之一。
声明:
Asha 和 Amar 正在玩电子游戏 SpaceKings。这是一个双人游戏,第二个玩家是助手。 Asha 在玩她最喜欢的游戏时需要您的帮助来最大化她的金币。两人都面对N个外星人。 Asha 和 Amar 都在同一个位置,外星人排在他们面前。 Asha 和 Amar 轮流射击外星人,她先走。在她的回合中,Asha 可以选择任何外星人射击(这意味着 Asha 可以选择跳过一个回合)。在轮到他时,阿马尔总是射杀离他最近的外星人,以帮助阿莎最大化她的金币。 Asha 和 Amar 不能射死外星人。
如果 Asha 向一个外星人射击,它的生命值会减少 P。如果 Amar 向一个外星人射击,它的生命值会减少 Q。如果一个外星人的生命值低于 1,它就会被杀死。第 i 个外星人以 Hi 生命值开始。如果 Asha 的一枪杀死了第 i 个外星人,Asha 将获得 Gi 金币,但如果 Amar 的一枪杀死了它,则不会获得金币。阿莎最多可以获得多少金币?
输入:
每个案例都以一行开始,其中包含三个用空格分隔的整数,分别代表 P、Q 和 N。然后是 N 行,第 i 行包含两个用空格分隔的整数,分别代表 Hi 和 Gi。外星人是按照他们与 Asha 和 Amar 的距离顺序给出的。换句话说,只有当所有外星人
输出 - 阿莎可以获得的最大金币数量
输入
20 60 3
80 100
80200
120 300
输出 - 500
说明: 阿莎应该放弃第一个外星人。在她的前两个回合中,她应该软化第三个外星人,将其降低到 80 马力,这样她就可以轻松地对第二个和第三个外星人进行最后一击
这里有一些其他的测试用例:
输入
50 60 2
40100
40 90
输出 - 100
输入
50 60 2
40100
40200
输出 - 200
输入
50 100 2
60 100
60200
输出 - 200
输入
50 400 2
60 100
190 200
输出 - 0
有人可以验证它是否正确吗?
def main():
inputString = input("")
inputList = inputString.split(" ")
ashaShot, amarShot, n = int(inputList[0]), int(inputList[1]), int(inputList[2])
hp = []
gold = []
for i in range(n):
hpThis, goldThis = input("").split()
hp.append(int(hpThis))
gold.append(int(goldThis))
def dp(origHp, currAsha):
if(all([i == 0 for i in origHp])):
return currAsha
firstAmarIndex = 0
for index, i in enumerate(origHp):
if(i>0):
firstAmarIndex = index
break
# firstTemp = hp[firstAmarIndex]
origHp[firstAmarIndex] = max(0, origHp[firstAmarIndex] - amarShot)
maxAns = 0
tempHp = origHp[:]
for index, i in enumerate(origHp):
if(i == 0):
continue
if(i<=ashaShot):
temp = tempHp[index]
tempHp[index] = 0
maxAns = max(maxAns, gold[index] + dp(tempHp[:], currAsha))
tempHp[index] = temp
else:
temp = tempHp[index]
tempHp[index]-=ashaShot
maxAns = max(maxAns, dp(tempHp[:], currAsha))
tempHp[index] = temp
maxAns = max(maxAns, dp(tempHp[:], currAsha))
return maxAns
maxAns = 0
# asha takes a random shot
tempHp = hp[:]
for index, i in enumerate(hp):
if(i<=ashaShot):
temp = tempHp[index]
tempHp[index] = 0
maxAns = max(maxAns, dp(tempHp[:], gold[index]))
tempHp[index] = temp
else:
temp = tempHp[index]
tempHp[index]-=ashaShot
maxAns = max(maxAns, dp(tempHp[:], 0))
tempHp[index] = temp
# asha skips her turn
maxAns = max(maxAns, dp(tempHp[:], 0))
print(maxAns)
main()```
【问题讨论】:
标签: python python-3.x dynamic-programming