Problem:


Score : 500 points

Problem Statement

Takahashi is at an all-you-can-eat restaurant.

The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.

The restaurant has the following rules:

You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.

You cannot order the same kind of dish more than once.

Until you finish eating the dish already served, you cannot order a new dish.

After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.

Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.

What is the maximum possible happiness achieved by making optimal choices?

Constraints

2 \leq N \leq 3000

1 \leq T \leq 3000

1 \leq A_i \leq 3000

1 \leq B_i \leq 3000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N T
A_1 B_1
:
A_N B_N

Output

Print the maximum possible happiness Takahashi can achieve.

Sample Input 1

2 60
10 10
100 100

Sample Output 1

110

By ordering the first and second dishes in this order, Takahashi's happiness will be 110.

Note that, if we manage to order a dish in time, we can spend any amount of time to eat it.

Sample Input 2

3 60
10 10
10 20
10 30

Sample Output 2

60

Takahashi can eat all the dishes within 60 minutes.

Sample Input 3

3 60
30 10
30 20
30 30

Sample Output 3

50

By ordering the second and third dishes in this order, Takahashi's happiness will be 50.

We cannot order three dishes, in whatever order we place them.

Sample Input 4

10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25

Sample Output 4

145



Sample input:
2 60
10 10
100 100


Sample output:
110

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, T: int, A: "List[int]", B: "List[int]"):
    # dp[i][w][超えたか超えてないか超えたら1]:= (i番目までの品物の中から重さが w を超えないように選んだときの、価値の総和の最大値,[index])

    AB = list(zip(A,B))
    AB.sort(key=lambda x:x[0])
    A = [AB[i][0] for i in range(N)]
    B = [AB[i][1] for i in range(N)]

    dp  = [[0 for _ in range(T)] for _ in range(N+1)]
    ans = 0
    for i in range(N):
        ans = max(ans,dp[i][T-1]+B[i])

        for j in range(0,T):

            if j >= A[i]: ##今回の商品がjよりも小さい
                dp[i+1][j] = max(dp[i][j-A[i]]+B[i],dp[i][j])
            else: ## 選ばない
                dp[i+1][j] = dp[i][j]
             
    print(ans)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    T = int(next(tokens))  # type: int
    A = [int()] * (N)  # type: "List[int]"
    B = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, T, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, T: int, A: "List[int]", B: "List[int]"):
    # dp[i][w][超えたか超えてないか超えたら1]:= (i番目までの品物の中から重さが w を超えないように選んだときの、価値の総和の最大値,[index])

    AB = list(zip(A,B))
    AB.sort(key=lambda x:x[0])
    A = [AB[i][0] for i in range(N)]
    B = [AB[i][1] for i in range(N)]

    dp  = [[0 for _ in range(T)] for _ in range(N+1)]
    ans = 0
    for i in range(N):
        for j in range(0,T):
            ans = max(ans,dp[i][j]+B[i])

            if j >= A[i]: ##今回の商品がjよりも小さい
                dp[i+1][j] = max(dp[i][j-A[i]]+B[i],dp[i][j])
            else: ## 選ばない
                dp[i+1][j] = dp[i][j]
             
    print(ans)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    T = int(next(tokens))  # type: int
    A = [int()] * (N)  # type: "List[int]"
    B = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, T, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N,T = map(int,input().split())
AB = [list(map(int,input().split())) for _ in range(N)]
AB.sort(key=lambda x:x[0])

dp = [[0]*T for i in range(N+1)]
ans = 0
for n in range(N):
    for w in range(T):
        ans = max(ans,dp[n][w]+AB[n][1])
        if w-AB[n][0]>=0:
            dp[n+1][w] = max(dp[n][w],dp[n][w-AB[n][0]]+AB[n][1])
        else:
            dp[n+1][w] = dp[n][w]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
data = input().split(" ")
n = int(data[0])
t = int(data[1])
ab = [[0,0]]
for i in range(n):
	data = input().split(" ")
	a = int(data[0])
	b = int(data[1])
	ab.append([a, b])
def d(n, t, item):
	c = [[0] * (t + 1) for i in range(n+1)]

	for i in range(1,n+1):
		for j in range(1, t+1):
			if item[i][0] <= j:
				if item[i][1] + c[i-1][j - item[i][0]] > c[i-1][j]:
					c[i][j] = item[i][1] + c[i-1][j - item[i][0]]
				else:
					c[i][j] = c[i-1][j]
			else:
				c[i][j] = c[i-1][j]

	return c[n][t]
max_score = 0
for i in range(n):
	m = ab.pop(1)
	score = m[1] + d(n-1, t-1, ab)
	if score > max_score:
		max_score = score
	ab.append(m)
print(max_score)

Submission status: Time Limit Exceeded

Solution code:
N,T=map(int,input().split())
d=[None]*N
for i in range(N):
  a,b=map(int,input().split())
  d[i]=[a,b]

d=sorted(d,key=lambda x:x[0])
dp=[-1]*(3000*2+5)
dp[0]=0
for i in range(len(d)):
  for j in range(T-1,-1,-1):
    if dp[j]!=-1:
      if dp[j]+d[i][1]>dp[j+d[i][0]]:
        dp[j+d[i][0]]=dp[j]+d[i][1]
      
print(max(dp))

Submission status: Time Limit Exceeded

Solution code:
import collections

n, t = map(int, input().split())
tpls = list(sorted(tuple(map(int, input().split())) for _ in range(n)))
a = [None] * n
b = [None] * n
for i in range(n):
    a[i], b[i] = tpls[i]

dp = [collections.defaultdict(int) for _ in range(n + 1)]
dp[0][0] = 0
for i in range(n):
    for cur in dp[i]:
        dp[i + 1][cur] = max(dp[i + 1][cur], dp[i][cur])
        if cur < t:
            dp[i + 1][cur + a[i]] = max(dp[i + 1][cur + a[i]], dp[i][cur] + b[i])
print(max(dp[n].values()))

Submission status: Time Limit Exceeded

Solution code:
N, T = map(int, input().split())
AB = [tuple(map(int, input().split())) for _ in range(N)]
AB.sort()
INF = float('inf')

dp = [-INF] * (T + 1)
dp[0] = 0

for a, b in AB:
    for t in range(T)[:: -1]:
        dp[min(T, t + a)] = max(dp[min(T, t + a)], dp[t] + b)

print(max(dp))

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")

def main():
    n, t = map(int, input().split())
    ab = []
    for _ in range(n):
        a, b = map(int, input().split())
        ab.append((a, b))
    ab.sort()
    dp = [0] * (t + 1)
    for a, b in ab:
        dp[t] = max(dp[t], dp[t - 1] + b)
        for i in range(t - 1, a - 1, -1):
            dp[i] = max(dp[i], dp[i - a] + b)
    print(dp[t])
    # print(dp)

main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict


n, t = map(int, input().split())

dish = []

for _ in range(n):
    time, point = map(int, input().split())
    dish.append([time, point])

dish.sort()
DP = [[0]*t for i in range(n+1)]
ans = defaultdict(int)

for i in range(1, n+1):
    time, point = dish[i-1]

    for j in range(t):
        DP[i][j] = max(DP[i-1][j], DP[i][j])
        if j + time >= t:
            ans[i] = max(DP[i-1][j]+point, ans[i])
            continue
        DP[i][j+time] = max((DP[i-1][j] + point), DP[i-1][j+time])

res = max(ans.values())
print(res)

Submission status: Time Limit Exceeded

Solution code:
def main():

    N, T = map(int, input().split())
    C = []
    for _ in range(N):
        A, B = map(int, input().split())
        C.append([B, A])
    # C.sort()

    dp = [[0, 0] for _ in range(T)]
    ans = 0
    for i in range(T):
        for j in range(N):
            if (dp[i][1] >> j) % 2 == 0:
                if i+C[j][1] > T-1:
                    ans = max(ans, dp[i][0] + C[j][0])
                else:
                    if dp[i][0]+C[j][0] > dp[i+C[j][1]][0]:
                        dp[i+C[j][1]][0] = dp[i][0]+C[j][0]
                        dp[i+C[j][1]][1] = (1 << j) | dp[i][1]
        ans = max(ans, dp[i][0])

    return ans

if __name__ == '__main__':
    print(main())

Submission status: Time Limit Exceeded

Solution code:
n, t = map(int, input().split())

a = [0]*(n)
b = [0]*(n)
dp = [0]*6666



for i in range(0, n):
	a[i], b[i] = map(int, input().split())

z = zip(a,b)
z = sorted(z,reverse=False)
#print(z)
a, b = zip(*z)

#print(a[:n])
#print(b[:n])

for i in range(0, n):
	for j in range(6000, a[i]-1, -1):
		if ((a[i] <= j) and ((j-a[i])<t)):
			dp[j] = max(dp[j], dp[j - a[i]] + b[i])

#print(dp)
print(max(dp))

Submission status: Time Limit Exceeded

Solution code:
import math

def main():

    N, T = map(int, input().split())
    C = []
    for _ in range(N):
        A, B = map(int, input().split())
        C.append([B, A])
    # C.sort()

    dp = [[0, 0] for _ in range(T)]
    ans = 0
    for i in range(T):
        for j in range(N):
            if (dp[i][1] >> j) % 2 == 0:
                if i+C[j][1] > T-1:
                    ans = max(ans, dp[i][0] + C[j][0])
                else:
                    if dp[i][0]+C[j][0] > dp[i+C[j][1]][0]:
                        dp[i+C[j][1]][0] = dp[i][0]+C[j][0]
                        dp[i+C[j][1]][1] = (1 << j) | dp[i][1]

    # print(dp)
    for i in range(T):
        ans = max(ans, dp[i][0])
    return ans

if __name__ == '__main__':
    print(main())

Submission status: Time Limit Exceeded

Solution code:
N, T = map(int, input().split())
items = [tuple(map(int, input().split())) for _ in range(N)]

items.sort()

ans = 0
dp = {0: 0}
for wi, vi in items:
    for w, v in dp.items():
        if w < T:
            v2 = v + vi
            if v2 > ans:
                ans = v2

    for w, v in list(dp.items()):
        w2 = w + wi
        if w2 <= T:
            v2 = v + vi
            if w2 in dp:
                if v2 > dp[w2]:
                    dp[w2] = v2
            else:
                dp[w2] = v2

v2 = max(dp.values())
ans = max(ans, v2)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

def solve():
    input = sys.stdin.readline
    N, T = map(int, input().split())
    food = [[int(i) for i in input().split()] for _ in range(N)]
    food.sort()
    DP = [[0 for _ in range(T)] for i in range(N + 1)]
    for i in range(N):
        a, b = food[i]
        for t in range(T):
            DP[i+1][t] = max(DP[i][t], DP[i+1][t])
            if t+a < T: DP[i+1][t+a] = max(DP[i+1][t+a], DP[i][t] + b)
    max_dish = 0
    for i in range(N):
        max_dish = max(max_dish, max(DP[i]) + food[i][1])
    print(max_dish)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
n,t=map(int,input().split())
listf= []
maxsat = 0
allset = set()
for i in range(n):
    tmp = [int(j) for j in input().split()]
    if tmp[1]>maxsat:
        maxsat = tmp[1]
    listf.append(tmp)
    
    allset.add(i)
    
if t == 1:
    ans = maxsat
else:
    roadf = {}
    roadset = {}
    roadf[0] = 0
    roadset[0] = set()
    
    for i in range(1,t):
        roadf[i] = roadf[i-1]
        roadset[i] = roadset[i-1]
        for j in range(n):
            time = listf[j][0]
            if time<=i:
                ind = i-time
                tmpoldset = set(roadset[ind])
                if j not in tmpoldset:
                    tmp = roadf[ind]+listf[j][1]
                    if tmp > roadf[i]:
                        roadf[i] = tmp
                        roadset[i] = tmpoldset
                        roadset[i].add(j)
    #print(roadf)
    #print(roadset)
    
    lastf =  roadf[t-1]
    lastset =  roadset[t-1]
    if len(lastset) == n:
        ans = lastf
    else:
        ans = lastf
        tmpmax = 0
        testset = allset-lastset
        for i in testset:
                tmpf = listf[i][1]
                if tmpf>tmpmax:
                    tmpmax = tmpf
                    
        ans += tmpmax
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(3001)
N, T = map(int, input().split())
As = []
Bs = []
for i in range(N):
    a, b = map(int, input().split())
    As.append(a)
    Bs.append(b)

memo = {}
def dp(i, t):
    if i >= N:
        return 0, set()
    if (i, t) in memo:
        return memo[(i, t)]
    a, b = As[i], Bs[i]
    ret, s = dp(i+1, t)
    if t > a:
        ret2, s2 = dp(i+1, t-a)
        ret2 += b
        s2 = s2 | {i}
        if ret2 > ret:
            ret = ret2
            s = s2
    memo[(i, t)] = ret, s
    return ret, s

ret, s = dp(0, T)
maxB = 0
for i in range(N):
    if i not in s:
        maxB = maxB if maxB > Bs[i] else Bs[i]
print(ret + maxB)

Submission status: Time Limit Exceeded

Solution code:
import math

def main():

    N, T = map(int, input().split())
    C = []
    for _ in range(N):
        A, B = map(int, input().split())
        C.append([B, A])
    C.sort()

    dp = [[0, 0] for _ in range(T)]
    ans = 0
    for i in range(T):
        for j in range(N):
            if (dp[i][1] >> j) % 2 == 0:
                if i+C[j][1] > T-1:
                    ans = max(ans, dp[i][0] + C[j][0])
                else:
                    if dp[i][0]+C[j][0] > dp[i+C[j][1]][0]:
                        dp[i+C[j][1]][0] = dp[i][0]+C[j][0]
                        dp[i+C[j][1]][1] = (1 << j) | dp[i][1]

    for i in range(T):
        ans = max(ans, dp[i][0])
    return ans



if __name__ == '__main__':
    print(main())

Submission status: Time Limit Exceeded

Solution code:
import copy


def main():
    n, t = map(int, input().split())
    f = [list(map(int, input().split())) for _ in range(n)]
    dp = [0 for i in range(t)]
    ls = [[] for i in range(t)]
    for i in range(n):
        for j in range(t - 1, -1, -1):
            if j - f[i][0] >= 0 and dp[j - f[i][0]] + f[i][1] > dp[j]:
                dp[j] = dp[j - f[i][0]] + f[i][1]
                ls[j] = copy.copy(ls[j - f[i][0]]) + [i]
    res = dp[t - 1]
    ll = ls[t - 1]
    fff = [0 for _ in range(n)]
    for sll in ll:
        fff[sll] = 1
    ff = [f[i][1] for i in range(n) if fff[i] == 0]
    if ff:
        return res + max(ff)
    else:
        return res


print(main())

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]

n, t = ril()
ls = rils(n)

dp = [[0] * t for _ in range(n + 1)]
for i in range(n + 1):
    for t0 in range(t):
        a, b = ls[i - 1]
        if i == 0 or t0 == 0:
            continue
        elif a <= t0:
            dp[i][t0] = max(dp[i - 1][t0], dp[i - 1][t0 - a] + b)
        else:
            dp[i][t0] = dp[i - 1][t0]

res = set()
val = dp[n][t - 1]
t0 = t - 1
for i in reversed(range(n)):
    a, b = ls[i]
    if val <= 0:
        break
    if val == dp[i][t0]:
        continue
    else:
        res.add(i)
        val -= b
        t0 -= a

remaining = [v for i, (_, v) in enumerate(ls) if i not in res]
if len(remaining) > 0:
    print(dp[n][t - 1] + max(remaining))
else:
    print(dp[n][t - 1])

Submission status: Time Limit Exceeded

Solution code:
import sys
def rec(i,j,sho):
    res=0
    if(i==n):
        res=0
    else:
        tisai=max(sho,w[i])
        if(j+tisai>w[i]):
            res=max(rec(i+1,j,sho) , rec(i+1,j-w[i],w[i])+v[i])
        else:
            res=rec(i+1,j,sho)
        return res

    #elif(j<w[i]):
    #    res=rec(i+1,j)
    #else:
    #    res=max(rec(i+1,j) , rec(i+1,j-w[i])+v[i])
    return res
    
n,t=map(int,input().split())
w=[]
v=[]
for i in range(n):
    temp1,temp2=map(int,input().split())
    w.append(temp1)
    v.append(temp2)
#print(w,v)
sys.setrecursionlimit(10**8)

print(rec(0,t,0))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, T: int, A: "List[int]", B: "List[int]"):
    # dp[i][w][超えたか超えてないか超えたら1]:= (i番目までの品物の中から重さが w を超えないように選んだときの、価値の総和の最大値,[index])

    dp  = [[[0,[]] for _ in range(T)] for _ in range(N+1)]

    for i in range(N):
        for j in range(0,T):
            if j >= A[i]: ##今回の商品がjよりも小さい
                if dp[i][j-A[i]][0]+B[i]>=dp[i][j][0]: ## 選ぶ
                    dp[i+1][j][0] = dp[i][j-A[i]][0]+B[i]
                    dp[i+1][j][1] = dp[i][j-A[i]][1]+[i]
                else:
                    dp[i+1][j]= dp[i][j]
            else: ## 選ばない
                dp[i+1][j] = dp[i][j]
    
    index = list(range(0,N))
    a = list(set(index)- set(dp[N][T-1][1]))
    
    max_add = 0
    for i in a:
        max_add = max(max_add,B[i]) 

    print(dp[N][T-1][0]+max_add)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    T = int(next(tokens))  # type: int
    A = [int()] * (N)  # type: "List[int]"
    B = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, T, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
import copy
def knapsack(N,W,weight,value):
  dp=[[999999999999 for i in range(W+1)] for j in range(N+1)]
  dp2=[]
  for i in range(N+1):
    x=[]
    for j in range(W+1):
      x.append([])
    dp2.append(x)
  for i in range(W+1): dp[0][i]=0
 
  for i in range(N):
    for w in range(W+1):
      if weight[i]<=w:
        if dp[i][w-weight[i]]+value[i]>dp[i][w]:
          dp[i+1][w]=dp[i][w-weight[i]]+value[i]
          x=copy.copy(dp2[i][w-weight[i]])
          x.append(i)
          dp2[i+1][w]=x
        else:
          dp[i+1][w]=dp[i][w]
          dp2[i+1][w]=dp2[i][w]
        
      else:
        dp[i+1][w]=dp[i][w]
        dp2[i+1][w]=dp2[i][w]
  return [dp[N][W],dp2[N][W]]
 
n,t=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]
a=[];b=[]
for i in range(n):
  a.append(l[i][0])
  b.append(l[i][1])
z=knapsack(n,t-1,a,b)
x=z[0];y=z[1]
L=[0 for i in range(n)]
m=0
for i in range(len(y)):
  L[y[i]]=1
M=[]
for i in range(n):
  if L[i]==0:
    M.append(b[i])
if len(M)==0:
  print(x)
else:
  print(x+max(M))

Submission status: Time Limit Exceeded

Solution code:
import sys
def rec(i,j,sho):
    res=0
    if(i==n):
        res=0
    else:
        tisai=max(sho,w[i])
        if(j+tisai>w[i]):
            res=max(rec(i+1,j,sho) , rec(i+1,j-w[i],sho)+v[i])
        else:
            res=rec(i+1,j,sho)
        return res

    #elif(j<w[i]):
    #    res=rec(i+1,j)
    #else:
    #    res=max(rec(i+1,j) , rec(i+1,j-w[i])+v[i])
    return res
    
n,t=map(int,input().split())
w=[]
v=[]
for i in range(n):
    temp1,temp2=map(int,input().split())
    w.append(temp1)
    v.append(temp2)
#print(w,v)
sys.setrecursionlimit(10**8)

print(rec(0,t,0))

Submission status: Time Limit Exceeded

Solution code:
n,t = map(int,input().split())
data = []
for i in range(n):
  ai,bi = map(int,input().split())
  data.append([ai,bi])
data.sort(key=lambda x:x[0],reverse = True)
z = data[0][1]
mx = 0
for i in range(n):
  if z > data[i][1]:
    z = data[i][1]
    continue
  l = [0 for _ in range(t)]
  for j in range(n):
    newl = []
    if j != i:
      for k in range(0,t):
        if data[j][0] > k:
          newl.append(l[k])
        else:
          newl.append(max(l[k],l[k-data[j][0]]+data[j][1]))
      l = newl
  score = l[t-1]+data[i][1]
  if score > mx:
    mx = score
print(mx)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin


def input():
    return stdin.readline()[:-1]


def intput():
    return int(input())


def sinput():
    return input().split()


def intsput():
    return map(int, sinput())


dishes = []
n, t = intsput()
for _ in range(n):
    dishes.append(list(intsput()))
    dishes[-1].append(dishes[-1][1] / dishes[-1][0])

maxweight = max([x[0] for x in dishes])
dishes.sort(key=lambda x: x[1], reverse=True)

dp = [[[0, 1]] * (t + 1) for _ in range(n + 1)]

for i in range(1, n + 1):
    for j in range(t):
        if dishes[i - 1][0] > j:
            dp[i][j] = dp[i - 1][j][:]
        else:
            val = max(dp[i - 1][j][0], dp[i - 1][j - dishes[i - 1][0]][0] + dishes[i - 1][1])
            dp[i][j] = [val]
            if val == dp[i - 1][j][0]:
                dp[i][j].append(dp[i - 1][j][1])
            else:
                if i == dp[i - 1][j - dishes[i - 1][0]][1]:
                    dp[i][j].append(i + 1)
                else:
                    dp[i][j].append(dp[i - 1][j - dishes[i - 1][0]][1])

rslt = dp[n][t - 1]

if rslt[1] <= n:
    vv = dishes[rslt[1] - 1][1]
else:
    vv = 0
print(rslt[0] + vv)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
N, T = list(map(int, input().split()))
ab_list = []
weight = []
value = []
for _ in range(N):
    a, b = list(map(int, input().split()))
    weight.append(a)
    value.append(b)

#  DPテーブル
dp = [[0] * (T - 1) for _ in range(N + 1)]
dp_3 = []
max_v = -float("inf")

for j in range(N):
    w_last = weight[j]
    v_last = value[j]
    for i in range(N):
        if i == j:
            continue
        for w in range((T - 1)):
            if w >= weight[i]:
                dp[i + 1][w] = max(dp[i][w - weight[i]] + value[i], dp[i][w])
            else:
                dp[i + 1][w] = dp[i][w]
    max_v = max(max_v, dp[N - 1][T - 2] + v_last)
ans = max_v
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, T: int, A: "List[int]", B: "List[int]"):
    # dp[i][w][超えたか超えてないか超えたら1]:= (i番目までの品物の中から重さが w を超えないように選んだときの、価値の総和の最大値,[index])

    dp  = [[[0,[]] for _ in range(T)] for _ in range(N+1)]

    for i in range(N):
        for j in range(0,T):
            if j >= A[i]: ##今回の商品がjよりも小さい
                if dp[i][j-A[i]][0]+B[i]>=dp[i][j][0]: ## 選ぶ
                    dp[i+1][j][0] = dp[i][j-A[i]][0]+B[i]
                    dp[i+1][j][1] = dp[i][j-A[i]][1] + [i]
                else:
                    dp[i+1][j][0] = dp[i][j][0]
                    dp[i+1][j][1] = dp[i][j][1]
            else: ## 選ばない
                dp[i+1][j][0] = dp[i][j][0]
                dp[i+1][j][1] = dp[i][j][1]
    
    index = list(range(0,N))
    a = list(set(index)- set(dp[N][T-1][1]))
    
    max_add = 0
    for i in a:
        max_add = max(max_add,B[i]) 

    print(dp[N][T-1][0]+max_add)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    T = int(next(tokens))  # type: int
    A = [int()] * (N)  # type: "List[int]"
    B = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, T, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n,t=map(int,input().split())
listf= []
maxsat = 0

for i in range(n):
    tmp = [int(j) for j in input().split()]
    if tmp[1]>maxsat:
        maxsat = tmp[1]
    listf.append(tmp)
    
if t == 1:
    ans = maxsat
else:
    roadf = {}
    roadset = {}
    roadf[0] = 0
    roadset[0] = set()
    
    for i in range(1,t):
        roadf[i] = roadf[i-1]
        roadset[i] = roadset[i-1]
        for j in range(n):
            time = listf[j][0]
            if time<=i:
                ind = i-time
                tmpoldset = set(roadset[ind])
                if j not in tmpoldset:
                    tmp = roadf[ind]+listf[j][1]
                    if tmp > roadf[i]:
                        roadf[i] = tmp
                        roadset[i] = tmpoldset
                        roadset[i].add(j)
    #print(roadf)
    #print(roadset)
    
    lastf =  roadf[t-1]
    lastset =  roadset[t-1]
    if len(lastset) == n:
        ans = lastf
    else:
        ans = lastf
        tmpmax = 0
        for i in range(n):
            if i not in lastset:
                tmpf = listf[i][1]
                if tmpf>tmpmax:
                    tmpmax = tmpf
                    
        ans += tmpmax
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-


def run(foods, time, idx):
  dp = [[0] * time for _ in range(len(foods) + 1)]

  for i, f in enumerate(foods):
    for j in range(time):
      if i != idx and j - f[0] >= 0:
        dp[i + 1][j] = max(dp[i][j - f[0]] + f[1], dp[i][j])
      else:
        dp[i + 1][j] = dp[i][j]
  return dp[-1][-1]


def main():
  n, time = map(int, input().split())
  foods = [tuple(map(int, input().split())) for _ in range(n)]
  value = 0

  for idx in range(len(foods)):
    value = max(run(foods, time, idx) + foods[idx][1], value)

  print(value)

if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
# E
import numpy as np
N, T = map(int, input().split())
# A=cost. B=value
A, B = np.array([input().split() for _ in range(N)], dtype=int).T

weight,value = A, B
# dp[i][w] = i番目までからwを超えないように選んだ時の最大値, まだ最後の食べ物を選んでない
d0 = np.zeros((N,T),int)
# dp[i][w] = i番目までからwを超えないように選んだ時の最大値, もう最後の食べ物を選んだ
d1 = np.zeros((N,T),int)
# 初期値として0番目の商品を加える
d0[0,weight[0]:] = value[0]
d1[0,:] = value[0]

for n in range(1, N):
  for w in range(T):
    if (w >= weight[n]):
      d0[n][w] = max(d0[n-1][w-weight[n]] + value[n], d0[n-1][w])
      d1[n][w] = max(d1[n-1][w-weight[n]] + value[n], d1[n-1][w], d0[n-1][w] + value[n])
    else:
      d0[n][w] = d0[n-1][w]
      d1[n][w] = max(d1[n-1][w], d0[n-1][w] + value[n])

print(d1[-1,-1])

Submission status: Time Limit Exceeded

Solution code:
import sys
def rec(i,j,sho):
    res=0
    if(i==n):
        res=0
    else:
        tisai=max(sho,w[i])
        if(j+tisai>w[i]):
            res=max(rec(i+1,j,sho) , rec(i+1,j-w[i],tisai)+v[i])
        else:
            res=rec(i+1,j,sho)
        return res

    #elif(j<w[i]):
    #    res=rec(i+1,j)
    #else:
    #    res=max(rec(i+1,j) , rec(i+1,j-w[i])+v[i])
    return res
    
n,t=map(int,input().split())
w=[]
v=[]
for i in range(n):
    temp1,temp2=map(int,input().split())
    w.append(temp1)
    v.append(temp2)
#print(w,v)
sys.setrecursionlimit(10**8)

print(rec(0,t,0))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from heapq import heappush, heappop
N, T = map(int, input().split())
dic = defaultdict(list)
ls = []
pre = []
log = [[1]*N]*T
dp = [0]*(T)
for i in range(N):
  a, b = map(int, input().split())
  ls += [(a,b)]
  if a<T:
    for j in range(T-1,a-1,-1):
      if dp[j-a]+b>dp[j]:
        dp[j] = dp[j-a]+b
        log[j] = log[j-a][:]
        log[j][i] = 0
  else:
    heappush(pre, -b)
m = 0
ind = -1
his = None
for j in range(T):
  if dp[j]>m:
    m = dp[j]
    ind = j
for c in range(N):
  if log[ind][c]:
    heappush(pre,-ls[c][1])

if pre:
  m -= heappop(pre)
print(m)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)

N, T = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]
AB.sort(key=lambda x: x[1]//x[0], reverse=True)

def dfs(i, sum, time, remain):
    global answer
    if i == min(N, 1000):
        if time < T and len(remain) >= 1:
            sum += AB[min(remain)][1]
        if sum > answer:
            answer = sum
    else:
        dfs(i+1, sum, time, remain)
        if time < T:
            dfs(i+1, sum + AB[i][1], time + AB[i][0], remain-{i})

answer = 0
dfs(0, 0, 0, set(range(N)))
print(answer)

Submission status: Time Limit Exceeded

Solution code:
import copy


def main():
    n, t = map(int, input().split())
    f = [list(map(int, input().split())) for _ in range(n)]
    dp = [0 for i in range(t)]
    ls = [[] for i in range(t)]
    for i in range(n):
        for j in range(t - 1, -1, -1):
            if j - f[i][0] >= 0 and dp[j - f[i][0]] + f[i][1] > dp[j]:
                dp[j] = dp[j - f[i][0]] + f[i][1]
                ls[j] = copy.copy(ls[j - f[i][0]])
                ls[j].append(i)
    res = dp[t - 1]
    ll = ls[t - 1]
    fff = [0 for _ in range(n)]
    for sll in ll:
        fff[sll] = 1
    ff = [f[i][1] for i in range(n) if fff[i] == 0]
    if ff:
        return res + max(ff)
    else:
        return res


print(main())

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline
    N, T = map(int, input().strip().split())
    foods = [list(map(int, input().strip().split())) for _ in range(N)]

    ans = 0
    before_dp = [[0] * T for _ in range(N)]
    for i, food in enumerate(foods):
        now_foods = foods[:i] + foods[i+1:]
        dp = before_dp[:i] + [[0] * T for _ in range(N-i)]
        for j, n_food in enumerate(now_foods):
            if j < i-1:
                continue
            n_a, n_b = n_food
            for k in range(T):
                if k < n_a:
                    dp[j+1][k] = dp[j][k]
                else:
                    dp[j+1][k] = max(dp[j][k], dp[j][k-n_a]+n_b)
        #print(dp[j+1])
        ans = max(ans, dp[-1][-1]+food[1])
        before_dp = dp
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import math

MOD=10**9+7

N,T=map(int,input().split())
l=[list(map(int,input().split())) for i in range(N)] 
l.sort(reverse=True)

dp1=[[-10**10 for i in range(T)] for i in range(N)]
dp2=[[0 for i in range(T)] for i in range(N)]

[a,b]=l[0]
dp1[0][0],dp2[0][0]=0,b
if a<T: dp1[0][a]=b

for i in range(1,N):
    [a,b]=l[i]
    m=min(a,T)
    for j in range(m):
        dp1[i][j]=dp1[i-1][j]
        dp2[i][j]=max(b,dp2[i-1][j])
    for j in range(m,T):
        p,q=dp1[i-1][j],dp1[i-1][j-a]+b
        if p<q:
            dp1[i][j]=q
            dp2[i][j]=dp2[i-1][j-a]
        elif p>q:
            dp1[i][j]=p
            dp2[i][j]=max(dp2[i-1][j],b)
        else:
            dp1[i][j]=p
            dp2[i][j]=max(dp2[i-1][j-a],dp2[i-1][j],b)

print(max( dp1[N-1][j]+dp2[N-1][j] for j in range(T) ) )

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
import copy
def knapsack(N,W,weight,value):
  dp=[[999999999999 for i in range(W+1)] for j in range(N+1)]
  dp2=[[set() for i in range(W+1)] for j in range(N+1)]
  for i in range(W+1): dp[0][i]=0
 
  for i in range(N):
    for w in range(W+1):
      if weight[i]<=w:
        if dp[i][w-weight[i]]+value[i]>dp[i][w]:
          dp[i+1][w]=dp[i][w-weight[i]]+value[i]
          x=copy.copy(dp2[i][w-weight[i]])
          x.add(i)
          dp2[i+1][w]=x
        else:
          dp[i+1][w]=dp[i][w]
          dp2[i+1][w]=dp2[i][w]
        
      else:
        dp[i+1][w]=dp[i][w]
        dp2[i+1][w]=dp2[i][w]
  return [dp[N][W],dp2[N][W]]
 
n,t=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]
a=[];b=[]
for i in range(n):
  a.append(l[i][0])
  b.append(l[i][1])
z=knapsack(n,t-1,a,b)
x=z[0];y=z[1]
M=[]
for i in range(n):
  if i not in y:
    M.append(b[i])
if len(M)==0:
  print(x)
else:
  print(x+max(M))