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:
import heapq
n, t = (int(x) for x in input().split())
food = []
for _ in range(n):
    food.append(tuple(int(x) for x in input().split()))

visited = set()
stack = []
heapq.heappush(stack,(0, set()))
ans = 0
while stack:
    cur_t, state = heapq.heappop(stack)
    if cur_t >= t or len(state) == n:
        score = sum(food[s][1] for s in state)
        ans = max(ans, score)
    else:
        for i, f in enumerate(food):
            if i not in state:
                new_state = state.union((i,))
                new_state_tup = tuple(sorted(new_state))
                if new_state_tup not in visited:
                    heapq.heappush(stack, (cur_t + f[0], new_state))
                    visited.add(new_state_tup)
print(ans)

Submission status: Time Limit Exceeded

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


def main(p):
    f = ff[:]
    mf = f.pop(p)
    dp = [[0 for i in range(t)] for j in range(n)]
    for i in range(n - 1):
        for j in range(t):
            if j - f[i][0] >= 0:
                dp[i + 1][j] = max(dp[i][j], dp[i][j - f[i][0]] + f[i][1])
            else:
                dp[i + 1][j] = dp[i][j]
    return dp[n - 1][t - 1] + mf[1]


res = 0
for i in range(n):
    res = max(res, main(i))

print(res)

Submission status: Time Limit Exceeded

Solution code:
# A Dynamic Programming based Python Program for 0-1 Knapsack problem 
# Returns the maximum value that can be put in a knapsack of capacity W
# ty geekforgeeks
def knapSack(W, wt, val, n, avoid): 
    K = [[0 for x in range(W+1)] for x in range(n+1)] 
  
    # Build table K[][] in bottom up manner 
    for i in range(n+1): 
        for w in range(W+1):
            if avoid != None:
                index = i if i <= avoid else i + 1
            else:
                index = i
            if i==0 or w==0: 
                K[i][w] = 0
            elif wt[index-1] <= w: 
                K[i][w] = max(val[index-1] + K[i-1][w-wt[index-1]],  K[i-1][w]) 
            else: 
                K[i][w] = K[i-1][w] 
  
    return K[n][W] 

N, T = map(int, input().split())
wts = [None for i in range(N)]
val = [None for i in range(N)]
for i in range(N):
    a, b = map(int, input().split())
    wts[i] = a
    val[i] = b

best = knapSack(T, wts, val, N, None)
for i in range(N):
    best = max(best, knapSack(T-1, wts, val, N - 1, i) + val[i])
print(best)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from collections import defaultdict

n, t = li()
ab = [tuple(li()) for _ in range(n)]
ans = 0

for i in range(n):

    dic = defaultdict(int)
    dic[0] = 0
    for ai, bi in ab[:i] + ab[i+1:]:
        newdic = defaultdict(int)
        keys = dic.keys()
        for time, value in dic.items():
            if time + ai < t and time + ai in keys:
                newdic[time + ai] = max(dic[time + ai], value + bi)
            elif time + ai < t:
                newdic[time + ai] = value + bi
            newdic[time] = max(newdic[time], value)
        dic = newdic

    ans = max(ans, max(dic.values()) + ab[i][1])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# A Dynamic Programming based Python Program for 0-1 Knapsack problem 
# Returns the maximum value that can be put in a knapsack of capacity W
# ty geekforgeeks
def knapSack(W, wt, val, n): 
    K = [[0 for x in range(W+1)] for x in range(n+1)] 
  
    # Build table K[][] in bottom up manner 
    for i in range(n+1): 
        for w in range(W+1): 
            if i==0 or w==0: 
                K[i][w] = 0
            elif wt[i-1] <= w: 
                K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w]) 
            else: 
                K[i][w] = K[i-1][w] 
  
    return K[n][W] 

N, T = map(int, input().split())
wts = [None for i in range(N)]
val = [None for i in range(N)]
for i in range(N):
    a, b = map(int, input().split())
    wts[i] = a
    val[i] = b

best = knapSack(T, wts, val, N)
for i in range(N):
    newW = wts[:i] + wts[i+1:]
    newV = val[:i] + val[i+1:]
    best = max(best, knapSack(T-1, newW, newV, N - 1) + val[i])
print(best)

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:
        mx = 0
        for i in range(t - 1, -1, -1):
            dpi = dp[i]
            if dpi > mx: mx = dpi
            if i - a >= 0:
                dp[i] = max(dpi, dp[i - a] + b)
        dp[t] = max(dp[t], mx + b)
    print(dp[t])
    # print(dp)

main()

Submission status: Time Limit Exceeded

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

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

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

for i in range(N):
    a,b = AB[i]
    for t in range(T):
        dp[i+1][t][0] = dp[i][t][0]
        dp[i+1][t][1] = dp[i][t][1][:]
        if t-a>=0:
            if dp[i+1][t][0] < dp[i][t-a][0] + b:
                dp[i+1][t][0] = dp[i][t-a][0]+b
                dp[i+1][t][1] = dp[i][t-a][1][:]
                dp[i+1][t][1].append(i)

ans0 = dp[N][-1][0]
ans = ans0
s = set(dp[N][-1][1])
for i in range(N):
    if i in s:continue
    ans = max(ans,ans0+AB[i][1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,t = map(int,input().split())
time = [-1 for i in range(6030)]
time[0] = 0
now = 0
lis = [list(map(int,input().split())) for i in range(n)]
lis.sort(key = lambda x:x[0])
for i in range(n):
    for j in range(t-1,-1,-1):
        if time[j] != -1:
            time[j+lis[i][0]] = max(time[j+lis[i][0]],time[j]+lis[i][1])
print(max(time))

Submission status: Time Limit Exceeded

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

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


dp = [[-10000000 for i in range((n+1)*3000)] for j in range(n+1)]
dp[0][0] = 0


for i in range(n):
  a = food[i][0]
  b = food[i][1]
  for j in range(t):
    eat = dp[i][j]+b
    next_time = j+a
    # print(j,next_time)
    if dp[i+1][next_time] < eat:
      dp[i+1][next_time] = eat
    if dp[i+1][j] < dp[i][j]:
      dp[i+1][j] = dp[i][j]

# for i in range(n):
#   for j in range(10,21):
#     print(dp[i][j],end=" ")
#   print()
print(max(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)
# input = sys.stdin.readline
from bisect import *
from collections import *
from heapq import *
import functools
import itertools
import math
INF = float('inf')
MOD = 10**9+7

N, T = map(int, input().split())
AB = [None] * N
for i in range(N):
    AB[i] = tuple(map(int, input().split()))
ans = 0
for k in range(N):
    dp = [[-INF]*(T+1) for i in range(N+1)]
    dp[0][0] = 0
    for i in range(N):
        if i == k:
            for j in range(T+1):
                dp[i+1][j] = dp[i][j]
            continue
        A, B = AB[i]
        for j in range(T+1):
            if A <= j:
                dp[i+1][j] = max(dp[i][j], dp[i][j-A]+B)
            else:
                dp[i+1][j] = dp[i][j]
    # print(dp)
    ans = max(dp[N][T], max(dp[N][:T])+AB[k][1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def solve(n, t, ab_list):
    ab_list_s = sorted(ab_list, key=lambda x: x[0])
    res = 0
    dp = [0] * t
    for i in range(n):
        for s in range(t - 1, -1, -1):
            if dp[s] > 0 or s == 0:
                u = s + ab_list_s[i][0]
                r = dp[s] + ab_list_s[i][1]
                if u >= t:
                    res = max(res, r)
                else:
                    dp[u] = max(dp[u], r)
    return max(res, max(dp))


def main():
    n, t = map(int, input().split())
    ab_list = []
    for _ in range(n):
        a, b = map(int, input().split())
        ab_list.append([a, b])
    res = solve(n, t, ab_list)
    print(res)


def test():
    assert solve(2, 60, [[10, 10], [100, 100]]) == 110
    assert solve(3, 60, [[10, 10], [10, 20], [10, 30]]) == 60
    assert solve(3, 60, [[30, 10], [30, 20], [30, 30]]) == 50


if __name__ == "__main__":
    test()
    main()

Submission status: Time Limit Exceeded

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

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

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

for i in range(N):
    a,b = AB[i]
    for t in range(T):
        dp[i+1][t] = dp[i][t]
        if t-a>=0:
            if dp[i+1][t][0] < dp[i][t-a][0] + b:
                dp[i+1][t] = (dp[i][t-a][0]+b,dp[i][t-a][1]+[i])

ans0 = dp[N][-1][0]
ans = ans0
s = set(dp[N][-1][1])
for i in range(N):
    if i in s:continue
    ans = max(ans,ans0+AB[i][1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys

    input = sys.stdin.readline

    n, t = map(int, input().split())  # t - 1まで注文OK
    ab = tuple(tuple(map(int, input().split())) for _ in range(n))

    ret = 0
    for last_dish, (_, last_b) in enumerate(ab):
        dp = [0] * t
        # dp[皿ID][時間] = 最大おいしさ
        # dp[T-1] + 残りで一番美味しいもの
        # 先にどの皿を最後に食べるか決めておいて、それ以外でdp
        # 3000回dp

        for dish, (a, b) in enumerate(ab):
            if dish == last_dish:
                continue
            for t_ in range(t - 1, a - 1, -1):
                dp[t_] = max(dp[t_], dp[t_ - a] + b)
        ret = max(ret, max(dp) + last_b)
    return ret


print(solve())

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    n,t = LI()
    aa = sorted([LI() for _ in range(n)])
    m = max(map(lambda x: x[0], aa))
    r = [0] * (t+m+1)
    for a,b in aa:
        for i in range(t-1,-1,-1):
            if r[i+a] < r[i] + b:
                r[i+a] = r[i] + b

    return max(r)


print(main())

Submission status: Accepted

Solution code:
#E
N,T=map(int,input().split())
A=[0 for i in range(N+1)]
B=[0 for i in range(N+1)]
for i in range(1,N+1):
    A[i],B[i]=map(int,input().split())

dp1=[[0 for i in range(6001)] for j in range(N+1)]
dp2=[[0 for i in range(6001)] for j in range(N+2)]

for i in range(1,N+1):
    for j in range(T+1):
        if j>=A[i]:
            dp1[i][j]=max(dp1[i-1][j],dp1[i-1][j-A[i]]+B[i])
        else:
            dp1[i][j]=dp1[i-1][j]

for i in range(N,0,-1):
    for j in range(T+1):
        if j>=A[i]:
            dp2[i][j]=max(dp2[i+1][j],dp2[i+1][j-A[i]]+B[i])
        else:
            dp2[i][j]=dp2[i+1][j]

ans=0
for i in range(1,N+1):
    for j in range(T):
        ans=max(ans,dp1[i-1][j]+dp2[i+1][T-1-j]+B[i])
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right
from itertools import accumulate

sys.setrecursionlimit(10**6)
INF = 10**12
m = 10**9 + 7


def main():
    N, T = map(int, input().split())
    AB = []
    for _ in range(N):
        AB.append(list(map(int, input().split())))
    AB.sort()

    dp = [0] * (T + 1)
    ans = 0
    for i in range(N-1):
        for j in range(T, -1, -1):
            if j + AB[i][0] <= T:
                dp[j + AB[i][0]] = max(dp[j + AB[i][0]], dp[j] + AB[i][1])
        ans = max(ans, dp[T-1]+AB[i+1][1])
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
I=lambda:int(input())
MI=lambda:map(int,input().split())
LI=lambda:list(map(int,input().split()))

N,T=MI()
dp=[[0]*(T+1) for _ in [0]*(N+1)]
food=[tuple(MI()) for _ in [0]*N]
food.sort()

for n in range(N):
    a,b=food[n]
    for t in range(T+1):
        if t<T:
            # たべる
            dp[n+1][min(t+a,T)]=max(dp[n][t]+b,dp[n+1][min(t+a,T)])
        # たべない
        dp[n+1][t]=max(dp[n][t],dp[n+1][t])
print(dp[N][T])

Submission status: Accepted

Solution code:
N,T=map(int,input().split())
L=[]
for i in range(N):
  a,b=map(int,input().split())
  L.append((a,b))
L.sort()

DP=[[0 for i in range(T)] for j in range(N+1)]

for i in range(1,N+1):
  for j in range(T):
    if i>0 and j-L[i-1][0]>=0:
      DP[i][j]=max(DP[i-1][j-L[i-1][0]]+L[i-1][1],DP[i-1][j])
    else:
      DP[i][j]=DP[i-1][j]
ans=0
for i in range(N+1):
  if i!=N:
    ans=max(ans,DP[i][T-1]+L[i][1])
  else:
    ans=max(ans,DP[i][T-1])

print(ans)

Submission status: Accepted

Solution code:
N,T=map(int,input().split())
L=[]
for i in range(N):
  a,b=map(int,input().split())
  L.append((a,b))
L.sort()

DP=[[0 for i in range(T)] for j in range(N)]

for i in range(N):
  a=L[i][0]
  b=L[i][1]
  for j in range(min(T,a)):
    DP[i][j]=DP[i-1][j]
  for j in range(min(T,a),T):
    DP[i][j]=max(DP[i-1][j-a]+b,DP[i-1][j])
    
ans=0
for i in range(N-1):
  ans=max(ans,DP[i][T-1]+L[i+1][1])
print(ans)

Submission status: Accepted

Solution code:

def main():
    N, T = map(int,input().split())
    A = [0]
    B = [0]

    for _ in range(N):
        a, b = map(int,input().split())
        A.append(a)
        B.append(b)

    dp1 = [[0] * (T + 1) for i in range(N + 1)]
    # dp1[i][t] = 1~i番目から選んでt分以内に食べるときの美味しさの和の最大値
    dp2 = [[0] * (T + 1) for i in range(N + 2)]
    # dp2[i][t] = i~N番目から選んでt分以内に食べるときの美味しさの和の最大値

    for i in range(1, N+1):
        for t in range(T+1):
            if t >= A[i]:
                dp1[i][t] = max(dp1[i-1][t], dp1[i-1][t-A[i]] + B[i])
            else:
                dp1[i][t] = dp1[i-1][t]

    for i in range(N, 0, -1):
        for t in range(T + 1):
            if t >= A[i]:
                dp2[i][t] = max(dp2[i + 1][t], dp2[i + 1][t - A[i]] + B[i])
            else:
                dp2[i][t] = dp2[i + 1][t]

    ans = dp1[N][T]
    for i in range(1, N+1): # 最後にi番目の料理を食べる
        for t in range(T):
            ans = max(ans, dp1[i-1][t] + dp2[i+1][T-1-t] + B[i])
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

t -= 1
dp1 = [[0] * (t+1) for _ in range(n+1)]
dp2 = [[0] * (t+1) for _ in range(n+2)]

# from top
for i in range(n):
    for time in range(t+1):
        if time - dishes[i][0] >= 0:
            dp1[i+1][time] = max(
                dp1[i][time-dishes[i][0]] + dishes[i][1],
                dp1[i][time]
            )
        dp1[i+1][time] = max(dp1[i][time], dp1[i+1][time])


for j in reversed(range(2, n+2)):
    i = j-2
    for time in range(t+1):
        if time - dishes[i][0] >= 0:
            dp2[j-1][time] = max(
                dp2[j][time-dishes[i][0]] + dishes[i][1],
                dp2[j][time]
            )
        dp2[j-1][time] = max(dp2[j][time], dp2[j-1][time])


ans = 0
for i in range(1, n+1):
    for time in range(t+1):
        ans = max(
            ans,
            dp1[i-1][time] + dishes[i-1][1] + dp2[i+1][t - time]
        )
print(ans)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
fs = [tuple(map(int, input().split())) for _ in range(N)]
fs = sorted(fs)
dp = [0] * 6005

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

Submission status: Accepted

Solution code:
from itertools import chain
N, T = map(int, input().split())
# A = [0]*(N+1)
# B = [0]*(N+1)
AB = [(0, 0)]
for i in range(1, N+1):
    a, b = map(int, input().split())
    # A[i] = a
    # B[i] = b
    AB.append((a, b))
AB.sort()
dp = [[-1]*(6000+1) for _ in range(N+1)]
#dp[i][t]: 注文後にt秒になっている時、i番目までを考慮したとき、
#の最大
dp[0][0] = 0
for i in range(1, N+1):
    a, b = AB[i]
    for t in range(T):
        dp[i][t+a] = max(dp[i][t+a], dp[i-1][t] + b)
        dp[i][t] = max(dp[i][t], dp[i-1][t])
print(max(chain.from_iterable(dp)))

Submission status: Accepted

Solution code:
"""
時間がかかる料理は、食べるとしたら最後に食べるのがベスト。
逆にいうと、その料理を食べるかどうかを検討する段階ではほかの料理は食べるかどうかの検討は終わっている状態。
なので、食べるのにかかる時間でソートしてナップサックすればよい。
"""

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

ans = 0
for i in range(N):
    a,b = AB[i]
    ans = max(ans,dp[-1]+b)
    for j in range(T-1,-1,-1):
        if j-a >= 0:
            dp[j] = max(dp[j],dp[j-a]+b)
print(ans)

Submission status: Accepted

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq

n,t =ma()
AB = []
am = 0
for i in range(n):
    a,b = ma()
    AB.append((a,b))
    am = max(am,a)

dp1 = [[0]*t for i in range(n+1)] #dp1[i][j] 0~i種類までで時間jまでに食べきれる最高スコア
for i in range(n):
    a,b = AB[i]
    #print(a,b)
    for j in range(t-1,-1,-1):
        dp1[i][j] = dp1[i-1][j]
        if j+a<t:
            dp1[i][j+a] = max(dp1[i-1][j]+b,dp1[i][j+a])

dp2 = [[0]*t for i in range(n+1)] ##dp2[i][j] i~n-1種類までで時間jまでに食べきれる最高スコア

for i in range(n):
    a,b = AB[n-i-1]
    for j in range(t-1,-1,-1):
        dp2[n-i-1][j] = dp2[n-i][j]
        if j+a<t:
            dp2[n-i-1][j+a] = max(dp2[n-i][j]+b,dp2[n-i-1][j+a])

tmp=0
for i in range(n):
    for j in range(t):
        tmp = max(tmp,AB[i][1] + dp1[i-1][j] +dp2[i+1][t-1-j])
print(tmp)

Submission status: Accepted

Solution code:
import sys
from collections import deque
from functools import lru_cache
import bisect
import copy
import heapq
import itertools
import math
import random
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


def main():
    N, T = read_values()
    P = sorted([tuple(read_values()) for _ in range(N)], key=lambda p: (p[0], -p[1]))

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

    for i, (a, b) in enumerate(P):
        for t in range(T + 1):
            if t < T:
                s = min(T, t + a)
                dp[i + 1][s] = max(dp[i + 1][s], dp[i][t] + b)
            dp[i + 1][t] = max(dp[i + 1][t], dp[i][t])
    print(max(dp[N]))


if __name__ == "__main__":
    main()

Submission status: Accepted

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[i][j]=(i番目までの料理をj分以下で食べ切れるように選んだときの、美味しさの総和の最大値)
dp = [[0 for _ in range(T)] for _ in range(N + 1)]
for i in range(1, N + 1):
    for j in range(T):
        # i番目の料理を食べることができる場合
        if j - AB[i - 1][0] >= 0:
            # 実際に料理を食べる場合、食べない場合
            dp[i][j] = max(dp[i - 1][j - AB[i - 1][0]] + AB[i - 1][1], dp[i - 1][j])
        # i番目の料理を食べることができない場合
        else:
            dp[i][j] = dp[i - 1][j]

ans = 0
# k番目の料理を最後に食べると考える(T-1分に注文する)
# k-1番目までの料理をT-1分の間に最適に食べる + k番目を食べる
for k in range(1, N + 1):
    tmp = dp[k - 1][T - 1] + AB[k - 1][1]
    ans = max(ans, tmp)

print(ans)

Submission status: Accepted

Solution code:
N,T=map(int,input().split())

ablist=[]
bsum=0
for _ in range(N):
  a,b=map(int,input().split())
  ablist.append((a,b))
  bsum+=b
ablist.sort()
  
dp=[[0]*T for _ in range(N+1)]
for i in range(1,N+1):
  a,b=ablist[i-1]
  for j in range(T):
    dp[i][j]=dp[i-1][j]
    if j-a>=0:
      dp[i][j]=max(dp[i][j],dp[i-1][j-a]+b)      
#print(dp[N])

if dp[N][T-1]==bsum:
  print(bsum)
else:
  answer=0
  for i in range(1,N+1):
    answer=max(answer,dp[i-1][T-1]+ablist[i-1][1])
  print(answer)

Submission status: Accepted

Solution code:
import sys


def main():
    N, T, *AB = map(int, sys.stdin.buffer.read().split())
    D = [(a, b) for a, b in zip(*[iter(AB)] * 2)]

    D.sort()

    dp = [0] * T
    ans = 0

    for i, (a, b) in enumerate(D[:-1]):
        for t in range(T - 1, a - 1, -1):
            if dp[t] < dp[t - a] + b:
                dp[t] = dp[t - a] + b
        if ans < dp[T - 1] + D[i + 1][1]:
            ans = dp[T - 1] + D[i + 1][1]

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, T, *AB = map(int, read().split())
    D = [(a, b) for a, b in zip(*[iter(AB)] * 2)]

    D.sort()

    dp = [0] * T
    ans = 0

    for i, (a, b) in enumerate(D[:-1]):
        for t in range(T - 1, a - 1, -1):
            if dp[t] < dp[t - a] + b:
                dp[t] = dp[t - a] + b
        if ans < dp[T - 1] + D[i + 1][1]:
            ans = dp[T - 1] + D[i + 1][1]

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

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

newdp = [0 for _ in range(T)]
ans = 0
from collections import deque
A = deque(A)
visited = [0]
while A:
  olddp = tuple(newdp)
  newdp = list(newdp)
  X = A.popleft()
  a = X[0]
  b = X[1]
  for v in visited:
    if v + a > T-1:
      ans = max(ans, olddp[v]+b)
    else:

      if newdp[v+a] == 0:
        visited.append(v+a)
      newdp[v+a] = max(olddp[v] + b, newdp[v+a])


if ans == 0:
  print(max(olddp))
else:
  print(ans)

Submission status: Accepted

Solution code:
n, t = map(int, input().split())
dp1 = [[-float("inf") for i in range(t)] for i in range(n + 1)]
dp1[0][0] = 0
dp2 = [[-float("inf") for i in range(t)] for i in range(n + 1)]
dp2[n][0] = 0
ab = []
for i in range(n):
    ab.append(list(map(int, input().split())))
for i in range(n):
    a, b = ab[i]
    for j in range(t - 1, -1, -1):
        if j >= a:
            dp1[i + 1][j] = max(dp1[i][j], dp1[i][j - a] + b)
        else:
            dp1[i + 1][j] = dp1[i][j]
for i in range(n + 1):
    for j in range(t - 1):
        dp1[i][j + 1] = max(dp1[i][j], dp1[i][j + 1])
for i in range(n - 1, -1, -1):
    a, b = ab[i]
    for j in range(t - 1, -1, -1):
        if j >= a:
            dp2[i][j] = max(dp2[i + 1][j], dp2[i + 1][j - a] + b)
        else:
            dp2[i][j] = dp2[i + 1][j]
for i in range(n + 1):
    for j in range(t - 1):
        dp2[i][j + 1] = max(dp2[i][j], dp2[i][j + 1])
ans = [max([dp1[i][j] + dp2[i + 1][t - 1 - j] + ab[i][1] for j in range(t)]) for i in range(n)]
print(max(ans))

Submission status: Accepted

Solution code:
import sys


# \n
def input():
    return sys.stdin.readline().rstrip()


def main():
    N, T = map(int, input().split())
    dp = [0] * (T + 1)
    AB = []
    for k in range(N):
        a, b = map(int, input().split())
        AB.append((a, b))

    AB.sort()
    maxdp = 0
    temp = 1
    for i in range(N):
        a, b = AB[i]  # a:time  b:value
        temp += a
        dp[T] = max(maxdp + b, dp[T])
        for j in range(min(T - 1, temp), a - 1, -1):
            if dp[j] < dp[j-a] +b:
                dp[j] = dp[j - a] + b
                maxdp = max(dp[j], maxdp)
    print(dp[T])


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys


# \n
def input():
    return sys.stdin.readline().rstrip()


def main():
    N, T = map(int, input().split())
    dp = [0] * (T + 1)
    AB = []
    for k in range(N):
        a, b = map(int, input().split())
        AB.append((a, b))

    AB.sort()
    maxdp = 0
    temp = 1
    for i in range(N):
        a, b = AB[i]  # a:time  b:value
        temp += a
        dp[T] = max(maxdp + b, dp[T])
        for j in range(min(T - 1, temp), a - 1, -1):
            dp[j] = max(dp[j], dp[j - a] + b)
            maxdp = max(dp[j], maxdp)
    print(dp[T])


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys


# \n
def input():
    return sys.stdin.readline().rstrip()


def main():
    N, T = map(int, input().split())
    dp = [0] * (T + 1)
    AB = []
    for k in range(N):
        a, b = map(int, input().split())
        AB.append((a, b))

    AB.sort()
    maxdp = 0
    temp =0
    for i in range(N):
        a, b = AB[i]  # a:time  b:value
        temp +=a
        dp[T] = max(maxdp + b, dp[T])
        for j in range(min(T - 1,temp+1), a - 1, -1):
            dp[j] = max(dp[j], dp[j - a] + b)
            maxdp = max(dp[j], maxdp)
    print(dp[T])


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys


# \n
def input():
    return sys.stdin.readline().rstrip()


def main():
    N, T = map(int, input().split())

    dp = [0] * (T + 1)

    AB = []

    for k in range(N):
        a, b = map(int, input().split())
        AB.append((a, b))

    AB.sort()
    maxdp = 0

    for i in range(N):
        a, b = AB[i]  # a:time  b:value

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

if __name__ == "__main__":
    main()

Submission status: Accepted

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

MAX = 10000
dish.sort()
dp = [[0] * MAX for _ in range(n+1)]

for i in range(n):
    time, value = dish[i]
    for j in range(t):
        dp[i+1][j+time] = max(dp[i+1][j+time], dp[i][j] + value)
    for j in range(MAX):
        dp[i+1][j] = max(dp[i+1][j], dp[i][j])

print(max(dp[n]))

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
dp = [[0 for j in range(T)] for i in range(N)]
W = []
V = []
for i in range(N):
    w, v = map(int, input().split())
    W += [w]
    V += [v]
    
W, V = zip(*sorted(zip(W, V), key=lambda x: x[0]))
for i in range(N-1):
    for j in range(T):
        if j - W[i] < 0 :
            dp[i+1][j] = dp[i][j]
        else:
            dp[i+1][j] = max(dp[i][j], dp[i][j-W[i]] + V[i])
ans = 0
for i in range(N):
    ans = max(ans, dp[i][-1] + V[i])
print(ans)