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: Accepted

Solution code:
def main():
  e=enumerate
  (n,t),*g=[list(map(int,t.split()))for t in open(0)]
  d=[0]
  g.sort()
  dp=[]
  d=[0]*t
  for a,b in g:
    p=d[:]
    for i in range(a,t):
      v=d[i-a]+b
      if v>p[i]:p[i]=v
    dp+=p,
    d=p
  a=m=0
  for(*_,v),(_,w)in zip(dp[-2::-1],g[::-1]):
    if w>m:m=w
    if v+m>a:a=v+m
  print(a)
main()

Submission status: Accepted

Solution code:
e=enumerate
(n,t),*g=[list(map(int,t.split()))for t in open(0)]
d=[0]
g.sort()
dp=[]
d=[0]*t
for a,b in g:
  p=d[:]
  for i in range(a,t):
    v=d[i-a]+b
    if v>p[i]:p[i]=v
  dp+=p,
  d=p
a=m=0
for(*_,v),(_,w)in zip(dp[-2::-1],g[::-1]):
  if w>m:m=w
  if v+m>a:a=v+m
print(a)

Submission status: Accepted

Solution code:
N,T=map(int,input().split())
x=[(0,0)] # x[0]
for i in range(1,N+1): # x[i]のiに対応させる
    x.append(tuple(map(int,input().split()))) # x[1]~x[N]

x.sort()
# print(x) #DB★

dp1=[[0 for j in range(T)] for i in range(N+2)] # 0~N+1 dp1[i]はx[1]からx[i]まで使用（dp1[0]は使用するx[i]なしの初期値，dp1[N+1]は余り→0で初期化していることが後で役に立つ）
for i in range(1,N+1): # dp1[0]は初期値なのでいじらない。dp1[N+1]は余りなので計算しない。dp1[N]まで計算するので，iはNまで
    for j in range(T): # 0分後からT-1分後まで計算する
        if x[i][0]>j:
            dp1[i][j]=dp1[i-1][j]
        else:
            dp1[i][j]=max(dp1[i-1][j],dp1[i-1][j-x[i][0]]+x[i][1])

cans=[dp1[i-1][T-1]+x[i][1] for i in range(1,N+1)]

# print(cans) #DB★ 

ans=max(cans)

print(ans)

Submission status: Accepted

Solution code:
N,T=map(int,input().split())
x=[None] # x[0]
for i in range(1,N+1): # x[i]のiに対応させる
    x.append(tuple(map(int,input().split()))) # x[1]~x[N]
# print(x) #DB★

dp1=[[0 for j in range(T)] for i in range(N+2)] # 0~N+1 dp1[i]はx[1]からx[i]まで使用（dp1[0]は使用するx[i]なしの初期値，dp1[N+1]は余り→0で初期化していることが後で役に立つ）
for i in range(1,N+1): # dp1[0]は初期値なのでいじらない。dp1[N+1]は余りなので計算しない。dp1[N]まで計算するので，iはNまで
    for j in range(T): # 0分後からT-1分後まで計算する
        if x[i][0]>j:
            dp1[i][j]=dp1[i-1][j]
        else:
            dp1[i][j]=max(dp1[i-1][j],dp1[i-1][j-x[i][0]]+x[i][1])

# print(dp1) #DB★

dp2=[[0 for j in range(T)] for i in range(N+2)] # 0~N+1 dp2[i]はx[i]からx[N]まで（x[N]からx[i]まで）使用（dp2[N+1]は使用するx[i]なしの初期値，dp2[0]は余り）
for i in range(N,0,-1): # dp2[N+1]は初期値なのでいじらない。dp2[0]は余りなので計算しない。dp2[1]まで計算するので，iは1まで
    for j in range(T):
        if x[i][0]>j:
            dp2[i][j]=dp2[i+1][j]
        else:
            dp2[i][j]=max(dp2[i+1][j],dp2[i+1][j-x[i][0]]+x[i][1])

# print(dp2) #DB★

cans=[0 for i in range(N+1)] # i番目の料理を最後に食べる場合の満足度の最大値
for i in range(1,N+1):
    cans[i]=max([dp1[i-1][j]+dp2[i+1][T-1-j] for j in range(T)])+x[i][1]

# print(cans) #DB★ 

ans=max(cans)

print(ans)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
A = [0] * T
B = [0] * T
for _ in range(N):
    a, b = map(int, input().split())
    for i in range(T)[::-1]:
        if i + a < T:
            A[i+a] = max(A[i+a], A[i] + b)
            B[i+a] = max(B[i+a], B[i] + b)
        B[i] = max(B[i], A[i] + b)
print(max(B))

Submission status: Accepted

Solution code:
import numpy as np
N, T = map(int, input().split())
AB = [tuple(map(int, input().split())) for n in range(N)]
AB.sort()

dp = np.zeros(T, dtype=int)
ans = 0
for a, b in AB:
    ans = max(ans, dp[-1]+b)
    np.maximum(dp[a:], dp[:-a]+b, out=dp[a:])
print(ans)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines


# rstrip().decode('utf-8')
# INF=float("inf")
# MOD=10**9+7
# sys.setrecursionlimit(2147483647)
# import math
import numpy as np
# import operator
# import bisect
# from heapq import heapify,heappop,heappush
# from math import gcd
# from fractions import gcd
# from collections import deque
# from collections import defaultdict
# from collections import Counter
# from itertools import accumulate
# from itertools import groupby
# from itertools import permutations
# from itertools import combinations
# from scipy.sparse import csr_matrix
# from scipy.sparse.csgraph import floyd_warshall
# from scipy.sparse.csgraph import csgraph_from_dense
# from scipy.sparse.csgraph import dijkstra
# map(int,input().split())


def main():
	N, T = map(int, input().split())
	AB = [list(map(int, input().split())) for _ in range(N)]
	AB = sorted(AB)
	
	dp = np.zeros(T, np.int64)
	ans = 0
	for a, b in AB:
		ans = max(ans, dp.max() + b)
		np.maximum(dp[a:], dp[:-a] + b, out=dp[a:])
	print(ans)



if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N,T=map(int,input().split())
D=[tuple(map(int,input().split())) for i in range(N)]
D.sort()

DP=[0]*(T+1)
ANS=0

for i in range(N):
    a,b=D[i]

    for j in range(T,a-1,-1):
        DP[j]=max(DP[j-a]+b,DP[j])

    for j in range(i+1,N):
        ANS=max(ANS,DP[T-1]+D[j][1])

print(ANS)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
N,T=map(int, sys.stdin.readline().split())
AB=[ map(int, sys.stdin.readline().split()) for _ in range(N) ]

AB.sort()

N=6005
dp=[ None for _ in range(N) ]
dp[0]=0

for a,b in AB:
    for i in range(N-1,-1,-1):
        if dp[i] is not None and i<T:
                dp[i+a]=max(dp[i+a],dp[i]+b)

print max(dp)

Submission status: Accepted

Solution code:
import numpy as np
 
N,T = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]
AB = sorted(AB)

dp = np.zeros(T,np.int64)  
ans = 0
for a, b in AB:
    ans = max(ans, dp.max() + b)
    np.maximum(dp[a:], dp[:-a] + b, out=dp[a:])
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
 
N,T = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]
AB = sorted(AB)

can_add = [0]*N
for n in range(N-1, 0, -1):
  x = can_add[n]
  y = AB[n][1]
  can_add[n-1] = x if x>y else y

dp = np.zeros(T,np.int64)  
ans = 0
for i, (a,b) in enumerate(AB):
  np.maximum(dp[a:], dp[:-a].copy()+b, out=dp[a:])
  x = dp.max() + can_add[i]
  if ans < x:
    ans = x
print(ans)

Submission status: Accepted

Solution code:
def knapsack_DP(N, W, weight, value):
    import numpy as np
    dishes = [(weight[i], value[i]) for i in range(N)]
    dishes = sorted(dishes, key=lambda x: x[0])
    dp = np.zeros(W, dtype=int)
    ans=0
    for w, v in dishes:
        ans=max(dp[-1]+v, ans)
        np.maximum(dp[:-w] + v, dp[w:], out=dp[w:]) 
    return ans

if __name__=="__main__":
    N, W = map(int, input().split())
    weight = []
    value = []
    for i in range(N):
        w, v= map(int, input().split())
        weight.append(w)
        value.append(v)
    print(knapsack_DP(N, W, weight, value))

Submission status: Accepted

Solution code:
def main():
    N, T = map(int, input().split())
    l = []
    for _ in range(N):
        a, b = map(int, input().split())
        l.append((a,b))
    l.sort(key=lambda x: x[0])
    m = [[0] * T for _ in range(N)]
    m[0] = [0 if t < l[0][0] else l[0][1] for t in range(T)]
    for i in range(1, N):
        t, v = l[i]
        for j in range(min(t, T)):
            m[i][j] = m[i-1][j]
        for j in range(t, T):
            m[i][j] = max(l[i][1] + m[i-1][j-t], m[i-1][j])
    return max(l[i][1] + m[i-1][-1] if i > 0 else l[i][1] for i in range(N))

print(main())

Submission status: Accepted

Solution code:
N, T=map(int, input().split())
lst=[list(map(int, input().split())) for _ in range(N)]
MAXN, MAXT=3001, 3001
dp1=[[0 for _ in range(MAXT)] for _ in range(MAXN+1)]
dp2=[[0 for _ in range(MAXT)] for _ in range(MAXN+1)]
for i in range(1, N+1):
  A, B=lst[i-1]
  for j in range(1, MAXT):
    dp1[i][j]=max(dp1[i-1][j], dp1[i-1][j-A]+B) if j>=A else dp1[i-1][j]
for i in range(N, 0, -1):
  A, B=lst[i-1]
  for j in range(1, MAXT):
    dp2[i][j]=max(dp2[i+1][j], dp2[i+1][j-A]+B) if j>=A else dp2[i+1][j]
ans=dp1[N-1][T-1]+lst[-1][1]
for i in range(1, N):
  A, B=lst[i-1]
  for j in range(T):
    ans=max(ans, dp1[i-1][j]+dp2[i+1][T-1-j]+B)
print(ans)

Submission status: Accepted

Solution code:
N,T = map(int,input().split())
import numpy as np
A,B = np.array([list(map(int,input().split())) for _ in range(N)]).T
dp1 = np.array([[0]*T for _ in range(N+1)])
rev_A,rev_B = A[::-1],B[::-1]
dp2 = np.array([[0]*T for _ in range(N+1)])


for i in range(1,N+1):
  a = A[i-1]
  rev_a = rev_A[i-1]
  b = B[i-1]
  rev_b = rev_B[i-1]
  
  dp1[i,:a] = dp1[i-1,:a]
  dp2[i,:rev_a] = dp2[i-1,:rev_a]
  dp1[i,a:] = np.fmax(dp1[i-1,a:],dp1[i-1,:-a]+b)
  dp2[i,rev_a:] = np.fmax(dp2[i-1,rev_a:],dp2[i-1,:-rev_a]+rev_b)

      
lis = [0]*N
for i in range(1,N+1):
  lis[i-1] = (np.max(dp1[i-1]+dp2[N-i][::-1]) + B[i-1])
 
    
print(max(lis))

Submission status: Accepted

Solution code:
import sys


def solve():
    readline = sys.stdin.buffer.readline
    mod = 10 ** 9 + 7
    n, t = list(map(int, readline().split()))
    ab = [list(map(int, readline().split())) for _ in range(n)]
    ab.sort()
    dp = [0] * (t + 1)
    for a, b in ab:
        dp[-1] = max(dp[-1], dp[-2] + b)
        for i in range(t - a - 1, -1, -1):
            dp[i + a] = max(dp[i + a], dp[i] + b)
    print(dp[-1])


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
from operator import itemgetter
from heapq import heapify, heappop, heappush
MAX_INT = int(10e15)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N, T = IL()
ab = [IL() for i in range(N)]
ab.sort(key=itemgetter(0))
#print(ab)

dp = [[0]*(T+1+3000+1) for _ in range(N+1)]
ans = 0
for i in range(N):
  for j in range(T+1+3000+1):
    time, deli = ab[i]
    if 0 <= j-time < T:
      dp[i + 1][j] = max(dp[i][j], dp[i][j - time] + deli)
    else:
      dp[i + 1][j] = dp[i][j]
    ans = max(ans, dp[i + 1][j])
print(ans)

#print(dp)

Submission status: Accepted

Solution code:
def solve():
    from collections import namedtuple
    from operator import attrgetter
    import sys

    input = sys.stdin.readline
    Dish = namedtuple('Dish', 'idx cost pt')

    n, t = map(int, input().split())
    dishes = []
    for idx in range(1, n + 1):
        cost, pt = map(int, input().split())
        dishes.append(Dish(idx=idx, cost=cost, pt=pt))

    dishes.sort(key=attrgetter('cost'))

    dp = [0] * t
    # dp[完食にかかる総時間]:= 美味しさの最大値

    ret = 0
    for dish in dishes:
        for cost_ in range(t - 1, -1, -1):
            ret = max(ret, dp[cost_] + dish.pt)
            if cost_ >= dish.cost:
                dp[cost_] = max(dp[cost_], dp[cost_ - dish.cost] + dish.pt)

    return ret


print(solve())

# コスト昇順ソートした皿で、DPする
# 各皿は最後の皿（コスト0で、ポイントだけ加算し、以降は皿を取れない）にすることができる
# 最後の皿を選んだ時点でのポイントのmax
# https://sen-comp.hatenablog.com/entry/2019/11/17/003150

Submission status: Accepted

Solution code:
n,t=map(int,input().split())
ab=[]
for i in range(n):
    ab.append(list(map(int,input().split())))
ab_r=list(reversed(ab))

dp1=[[0 for j in range(t)] for i in range(n+1)]
dp2=[[0 for j in range(t)] for i in range(n+1)]

for i in range(n):
    for j in range(t-1):
        if ab[i][0] <= j:
            dp1[i+1][j] = max(dp1[i][j],dp1[i][j-ab[i][0]]+ab[i][1])
        else:
            dp1[i+1][j] = dp1[i][j]
            
        if ab_r[i][0] <= j:
            dp2[i+1][j] = max(dp2[i][j],dp2[i][j-ab_r[i][0]]+ab_r[i][1])
        else:
            dp2[i+1][j] = dp2[i][j]
            
m=0
for i in range(1,n+1):
    for j in range(t-1):
        m=max(m,dp1[i-1][j]+dp2[n-i][t-1-j]+ab[i-1][1])
print(m)

Submission status: Accepted

Solution code:
def solve():
    from collections import namedtuple
    import sys

    input = sys.stdin.readline
    Dish = namedtuple('Dish', 'idx cost pt')

    n, t = map(int, input().split())
    dishes = []
    for idx in range(1, n + 1):
        cost, pt = map(int, input().split())
        dishes.append(Dish(idx=idx, cost=cost, pt=pt))

    dp = [[0] * 2 for _ in range(t)]
    # dp[完食にかかる総時間][最後の皿を選んだか]:= 美味しさの最大値

    for dish in dishes:
        for cost_ in range(t - 1, -1, -1):
            dp[cost_][True] = max(dp[cost_][True], dp[cost_][False] + dish.pt)
            if cost_ >= dish.cost:
                dp[cost_][False] = max(dp[cost_][False], dp[cost_ - dish.cost][False] + dish.pt)
                dp[cost_][True] = max(dp[cost_][True], dp[cost_ - dish.cost][True] + dish.pt)

    return max(dp[cost_][True] for cost_ in range(t))


print(solve())

# 最後の皿を選んだかフラグを設ける
# https://sen-comp.hatenablog.com/entry/2019/11/17/003150

Submission status: Accepted

Solution code:
import numpy as np


if __name__ == '__main__':
    # input
    N, T = map(int,input().split())
    menu = list()
    for i in range(N):
        menu_i = tuple(map(int,input().split()))
        menu.append(menu_i)
    menu.sort()
    dp = np.zeros(T, int)
    ans = 0
    # print(N,T,menu)

    for ab in menu:
        # print(ab[0],ab[1])
        ans = max(ans, dp[-1]+ab[1])
        dp[ab[0]:] = np.maximum(dp[ab[0]:], dp[:-ab[0]] + ab[1])
    print(ans)

Submission status: Accepted

Solution code:
def solve():
    from collections import namedtuple
    import sys

    input = sys.stdin.readline
    Dish = namedtuple('Dish', 'idx cost pt')

    n, t = map(int, input().split())
    dishes = []
    for idx in range(1, n + 1):
        cost, pt = map(int, input().split())
        dishes.append(Dish(idx=idx, cost=cost, pt=pt))

    dp_ht = [[0] * t for _ in range(n + 2)]  # head->tail
    dp_th = [[0] * t for _ in range(n + 2)]  # tail->head
    # dp[注文可能な範囲の端][完食にかかる総時間]:= 美味しさの最大値

    for dish in dishes:
        for cost_ in range(t):
            if cost_ >= dish.cost:
                dp_ht[dish.idx][cost_] = max(dp_ht[dish.idx - 1][cost_],
                                             dp_ht[dish.idx - 1][cost_ - dish.cost] + dish.pt)
            else:
                dp_ht[dish.idx][cost_] = dp_ht[dish.idx - 1][cost_]

    for dish in reversed(dishes):
        for cost_ in range(t):
            if cost_ >= dish.cost:
                dp_th[dish.idx][cost_] = max(dp_th[dish.idx + 1][cost_],
                                             dp_th[dish.idx + 1][cost_ - dish.cost] + dish.pt)
            else:
                dp_th[dish.idx][cost_] = dp_th[dish.idx + 1][cost_]

    ret = 0
    for last_dish in dishes:
        for cost_ in range(t):
            ret = max(ret, dp_ht[last_dish.idx - 1][cost_] + dp_th[last_dish.idx + 1][t - 1 - cost_] + last_dish.pt)
    return ret


print(solve())

Submission status: Accepted

Solution code:
def knapsack(n, w, info):
    # dp[i][j] := i番目までの品物の中から重さの総和がjを超えないように選んだときの、
    #             価値の総和の最大値
    dp = [[0]*(w + 1) for i in range(n + 1)]
 
    for i in range(n):
        for j in range(w + 1):
            weight, value = info[i]
            if j < weight:
                dp[i + 1][j] = dp[i][j]
            else:
                dp[i + 1][j] = max(dp[i][j], dp[i][j - weight] + value)
    return dp
  
n, t = map(int, input().split())
info = [list(map(int, input().split())) for i in range(n)]

dp = knapsack(n, t, info)
dq = knapsack(n, t, info[::-1])
ans = 0
for i in range(n):
    for j in range(t):
        ans = max(dp[i][j] + dq[n-(i+1)][t-(j+1)] + info[i][1], ans)
print(ans)

Submission status: Accepted

Solution code:
def knapsack(n, w, info):
    # dp[i][j] := i番目までの品物の中から重さの総和がjを超えないように選んだときの、
    #             価値の総和の最大値
    dp = [[0]*(w + 1) for i in range(n + 1)]

    for i in range(n):
        for j in range(w + 1):
            weight, value = info[i]
            if j < weight:
                dp[i + 1][j] = dp[i][j]
            else:
                dp[i + 1][j] = max(dp[i][j], dp[i][j - weight] + value)
    return dp



n, t = map(int, input().split())
info = [list(map(int, input().split())) for i in range(n)]

ans = 0
if t == 1:
    for i in range(n):
        ans = max(ans, info[i][1])
    print(ans)
    exit()

info = sorted(info)
dp = knapsack(n, t, info)
ruiseki_max = [0]*(n+1)

for i in range(n)[::-1]:
    ruiseki_max[i] = max(ruiseki_max[i+1], info[i][1])

ans = 0
for i in range(n+1):
    ans = max(dp[i][-2] + ruiseki_max[i], ans)
print(ans)

Submission status: Accepted

Solution code:
import sys
n, t = [int(i) for i in sys.stdin.readline().split()]
ls = []
for k in range(n):
    a, b = [int(i) for i in sys.stdin.readline().split()]
    ls.append((a, b))
memo_ls = [[0 for i in range(t)] for j in range(n)]
another_memo_ls = [[-1 for i in range(t)] for j in range(n)]
ls = sorted(ls, key=lambda x:x[0])
a_ls, b_ls = zip(*ls)

for j in range(n):
    a, b = ls[j]
    for i in range(t):
        if j == 0:
            if a <= i:
                memo_ls[j][i] = b
                another_memo_ls[j][i] = j
            continue
        if a <= i:
            if memo_ls[j-1][i-a] + b > memo_ls[j-1][i]:
                memo_ls[j][i] = memo_ls[j-1][i-a] + b
                another_memo_ls[j][i] = j
            else:
                memo_ls[j][i] = memo_ls[j-1][i]
                another_memo_ls[j][i] = -1
        else:
            memo_ls[j][i] = memo_ls[j - 1][i]
            another_memo_ls[j][i] = -1
best = memo_ls[-1][-1]
for i in range(n-1):
    score = memo_ls[i][-1] + b_ls[i+1]
    best = max(best, score)
print(best)

Submission status: Accepted

Solution code:
import sys
from copy import deepcopy
import itertools
input = sys.stdin.readline

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

"""
作戦：最適解が求まっている時、それを食べる順序を（ラストオーダー以外は）変更しても問題なし。
そこで注文順は（ラストオーダー以外）食べる時間が昇順であるとして良い。
具体的には、ラストオーダーkを決める ⇒ 0,...,k-1の中で満足度を最大にする
ここまで落とし込めばあとはナップサック問題。
"""

"""
dp[i][j] = 0~i 番目の料理で j 分以内に完食できる美味しさの合計の最大値
"""

dp = [[0] * T for _ in range(N)]
a_0, b_0 = dish[0]
if a_0 < T:
	for j in range(a_0, T):
		dp[0][j] = b_0

for i in range(1, N):
	a, b = dish[i]
	for j in range(1, T):
		if j >= a:
			dp[i][j] = max(dp[i-1][j], dp[i-1][j-a] + b)
		else:
			dp[i][j] = dp[i-1][j] #ここ忘れてた！

#print(dp)


ans = b_0
for k in range(1, N):
	ans = max(ans, dp[k-1][T-1] + dish[k][1])

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter

N, T = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]

AB.sort(key=itemgetter(0))

dp = [[0 for _ in range(N+1)] for _ in range(T+1)]
# 重さwまで品物nまででで最大になる価値
C = []

for n in range(N): # 品物nまでの世界で決めていく
    a, b = AB[n]
    for w in range(T):
        if a > w: # カバンに入りきらないなら入れられない
            dp[w][n+1] = dp[w][n]
        else: #カバンに入れられる可能性があるなら
            if b+dp[w-a][n] >= dp[w][n]:
                dp[w][n+1] = dp[w-a][n] + b
            else:
                dp[w][n+1] = dp[w][n]
    C.append(dp[T-1][n]+b)

ans = max(C)
print(ans)

Submission status: Accepted

Solution code:
n,t=map(int,input().split())
s=[list(map(int,input().split())) for _ in range(n)]

dp=[[0]*(t) for i in range(n+1)]
s.sort()


for i in range(n):
    for j in range(t):
        if j-s[i][0]>=0:
            dp[i+1][j]=max(dp[i][j],dp[i][j-s[i][0]]+s[i][1])

        else:
            dp[i+1][j]=dp[i][j]

ans=0
for i in range(n):
    ans=max(ans,dp[i][t-1]+s[i][1])

print(ans)