Trying to solve piggy_bank and similar DP problems using Python3 and keep getting TLE.
Checked google for best algorithm and it seems the same as mine.
Note: got TLE even when read entire input with sys.stdin.read()
import sys
infinity = 9999999
def generate1(w):
return [0]+[infinity]*w
count = int(sys.stdin.readline())
for rnd in range(count):
e1,e2 = sys.stdin.readline().split(" ")
total_w = int(e2)-int(e1)
list1 = generate1(total_w)
rang = int(sys.stdin.readline())
s2 = [[int(i) for i in sys.stdin.readline().split(" ")] for rnd1 in range(rang)]
s2.sort(key=lambda x: x[1])
for j in range(0,total_w):
if list1[j]==infinity:
continue
for v,w in s2:
if w+j > total_w:
break
else:
list1[j+w]=min(list1[j+w],list1[j]+v)
if list1[-1]==infinity:
print("This is impossible.")
else:
print("The minimum amount of money in the piggy-bank is %d." % list1[-1])
created
last reply
- 4
replies
- 882
views
- 3
users