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:
import sys
input = sys.stdin.readline

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

    items.sort()

    capW = T-1
    dp = [0] * (capW+1)
    ans = 0
    for wi, vi in items:
        ans = max(ans, dp[-1]+vi)
        for w in reversed(range(wi, capW+1)):
            v0 = dp[w-wi] + vi
            if v0 > dp[w]:
                dp[w] = v0

    print(ans)


solve()

Submission status: Accepted

Solution code:
from sys import stdin
def main():
    #入力
    readline=stdin.readline
    n,t=map(int,readline().split())
    li=[list(map(int,readline().split())) for _ in range(n)]
    li.sort()
    a=[0]*n
    b=[0]*n
    for i in range(n):
        a[i],b[i]=li[i][0],li[i][1]

    #ナップサックDP
    inf=-10**9
    dp=[[inf]*(t+1) for _ in range(n+1)]
    dp[0][0]=0
    for i in range(n):
        for j in range(t+1):
            #i番目を食べる
            if j!=t:
                dp[i+1][min(t,j+a[i])]=max(dp[i+1][min(t,j+a[i])],dp[i][j]+b[i])
            
            #i番目を食べない
            dp[i+1][j]=max(dp[i+1][j],dp[i][j])

    print(max(dp[n]))

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
from sys import stdin
def main():
    #入力
    readline=stdin.readline
    n,t=map(int,readline().split())
    li=[list(map(int,readline().split())) for _ in range(n)]
    li.sort()
    a=[0]*n
    b=[0]*n
    for i in range(n):
        a[i],b[i]=li[i][0],li[i][1]

    #ナップサックDP
    inf=-float("inf")
    dp=[[inf]*(t+1) for _ in range(n+1)]
    dp[0][0]=0
    for i in range(n):
        for j in range(t+1):
            #i番目を食べる
            if j!=t:
                dp[i+1][min(t,j+a[i])]=max(dp[i+1][min(t,j+a[i])],dp[i][j]+b[i])
            
            #i番目を食べない
            dp[i+1][j]=max(dp[i+1][j],dp[i][j])

    print(max(dp[n]))

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
n,T = map(int, raw_input().split(' '))
dishes = [map(int, raw_input().split(' ')) for _ in range(n)]

#print n,T
#print dishes
h = [0 for iii in range(T + 1)]
dishes.sort(key = lambda x:x[0])
m = dishes[0][1] if len(dishes) == 1 else 0
for u,v in dishes:
	m = max(m , h[T-1] + v)
	for tt in range(T - 1, -1, -1):
		if tt - u >= 0:
			h[tt] = max(h[tt], v + h[tt - u])
		
print m

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])
import numpy as np
ans=0
dp=np.zeros(t,np.int64)
# dp[i]:時間合計i以内に食べれる料理のおいしさ総和の最大
for i in range(n):
  a,b=ab[i]
  ans=max(ans,dp[-1]+b)
  dp[a:]=np.maximum(dp[a:],dp[:-a]+b)
print(ans)

Submission status: Accepted

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

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

for i in range(1, T+3001):
    for j in range(N):
        if 0 <= i - K[j][0] <= T-1:
            dp[i][j+1] = max(dp[i - K[j][0]][j]+K[j][1], dp[i][j])
        else:
            dp[i][j+1] = dp[i][j]

ans = 0
for i in range(1,T+3001):
    ans = max(dp[i][N],ans)
print(ans)

Submission status: Accepted

Solution code:
import sys

input = lambda: sys.stdin.readline().rstrip()


def solve():
    N, T = map(int, input().split())
    AB = sorted([list(map(int, input().split())) for _ in range(N)])
    A = [0] * (N + 1)
    B = [0] * (N + 1)
    for i in range(N):
        A[i + 1], B[i + 1] = AB[i]

    a_max = max(A)
    t_max = T - 1 + a_max
    dp = [[0 for _ in range(t_max + 1)] for _ in range(N + 1)]

    for i in range(N):
        for j in range(t_max + 1):
            if 0 <= (j - A[i + 1]) and (j - A[i + 1]) < T:
                dp[i + 1][j] = max(dp[i + 1][j], dp[i][j], dp[i][j - A[i + 1]] + B[i + 1])
            else:
                dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])

    ans = 0
    for d in dp:
        ans = max(ans, max(d))

    print(ans)

    # for i in range(t_max + 1):
    #     print("{:03},".format(i), end='')
    # print('')
    # for d in dp:
    #     for a in d:
    #         print("{:03},".format(a), end='')
    #     print('')


if __name__ == '__main__':
    solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#ALL you can eat 
#0-1 なっぷサック問題をとく* N

#要領T-1のバックと　大きさがA,価値がBの荷物がNこずつある。　この時これらを使って価値をT-1をこえない範囲で最大にする方法を考える。


#dpl[N][V]=1番目からN番目までの荷物を用いて、重さをVにする上で実現可能な価値の最大値
N,T=map(int,input().split())
d=[]
for i in range(N):
    a,b=map(int,input().split())
    d.append((a,b))
dpl=[[0 for i in range(T)] for j in range(N+1)]
for i in range(N):
    weight,value=d[i]
    for j in range(T):
        if j>=weight:
            dpl[i+1][j]=max(dpl[i][j],dpl[i][j-weight]+value)
        else:
            dpl[i+1][j]=dpl[i][j]

            
#dpr[K][V]=K番目からN番目までの荷物を用いて、重さをVにする上で実現可能な価値の最大値
dpr=[[0 for i in range(T)] for j in range(N+2)]
for i in range(1,N+1):
    weight,value=d[-i]
    for j in range(T):
        if j>=weight:
            dpr[N+1-i][j]=max(dpr[N+2-i][j],dpr[N+2-i][j-weight]+value)
        else:
            dpr[N+1-i][j]=dpr[N+2-i][j]

#dpr[K][V]=K番目からN番目までの荷物を用いて重さをV以下にする上で実現可能な価値の最大値にする
for i in range(1,N+1):
    for j in range(1,T):
        dpr[i][j]=max(dpr[i][j],dpr[i][j-1])
    
ans=0
for i in range(N):
    sub=d[i][1]
    #i+1番目の物を使わない
    add=0
    for j in range(T):
        add=max(add,dpl[i][j]+dpr[i+2][T-1-j])
    sub+=add
    ans=max(sub,ans)
print(ans)

Submission status: Accepted

Solution code:
N,T=map(int,input().split())
A,B=[],[]
for i in range(N):
    a,b=map(int,input().split())
    A.append(a);B.append(b)
dp=[[0,0] for i in range(T)]

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

Submission status: Accepted

Solution code:
#dp[n][t]=max(dp[n-1][t],dp[n-1][t-A[n]]+B[n])
#dp[0][t]=0, dp[n][0]=0,0<=t<=T+max(B)-1, 0<=n<=N
def solve():
    N, T = map(int, input().split())
    X = [list(map(int, input().split())) for _ in range(N)]
    X.sort()
    dp = [[0]*(T+3000) for _ in range(N+1)]
    for n in range(1,N+1):
        for t in range(1,T+X[n-1][0]):
            dp[n][t]=dp[n-1][t]
            if t>=X[n-1][0]:
                dp[n][t]=max(dp[n][t],dp[n-1][t-X[n-1][0]]+X[n-1][1])
    ans = max(dp[N])
    return ans
print(solve())

Submission status: Accepted

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N,T = LI()
    A = [LI() for _ in range(N)]
    A.sort()
    dp = [[0] * (T+1) for _ in range(N+1)]

    for i in range(1,N+1):
        for j in range(1,T+1):
            a,b = A[i-1]
            if j == T:
                dp[i][j] = max(dp[i-1][j],dp[i-1][j-1]+b)
                continue
            if j < a:
                dp[i][j] = dp[i-1][j]
            else:
                dp[i][j] = max(dp[i-1][j],dp[i-1][j-a]+b)
    print(dp[-1][T])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from operator import itemgetter

    n, t = list(map(int, readline().split()))
    mat = [list(map(int, readline().split())) for _ in range(n)]
    dp1 = [[0] * t for _ in range(n + 2)]
    dp2 = [[0] * t for _ in range(n + 2)]

    for i, vec in enumerate(mat):
        a = vec[0]
        b = vec[1]
        for time in range(t):
            if time + a < t:
                dp1[i + 1][time + a] = max(dp1[i][time + a], dp1[i][time] + b)
            dp1[i + 1][time] = max(dp1[i][time], dp1[i + 1][time])

    for j, vec in enumerate(mat[::-1]):
        i = n + 1 - j
        a = vec[0]
        b = vec[1]
        for time in range(t):
            if time + a < t:
                dp2[i - 1][time + a] = max(dp2[i][time + a], dp2[i][time] + b)
            dp2[i - 1][time] = max(dp2[i][time], dp2[i - 1][time])

    ans = 0
    for i, vec in enumerate(mat, 1):
        val = vec[1]
        for j in range(t):
            temp = dp1[i - 1][j] + dp2[i + 1][t - j - 1] + val
            ans = max(ans, temp)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from operator import itemgetter

    n, t = list(map(int, readline().split()))
    mat = [list(map(int, readline().split())) for _ in range(n)]
    mat.sort(key=itemgetter(0))
    dp = [[0] * t for _ in range(n + 1)]
    ans = 0

    for dish, vec in enumerate(mat):
        a = vec[0]
        b = vec[1]
        for time in range(t):
            dp[dish + 1][time] = max(dp[dish + 1][time], dp[dish][time])
            if time + a >= t:
                ans = max(ans, dp[dish][time] + b)
            else:
                dp[dish + 1][time + a] = max(dp[dish + 1][time + a], dp[dish][time] + b)

    ans = max(max(dp[n]), ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
n,t = map(int,readline().split())
f = []
m = 0
for i in range(n):
  p,q = map(int,readline().split())
  m = max(m,p)
  f.append((p,q))
  
f.sort()
dp = [[0]*(t+m) for i in range(n+1)]

for i,c in enumerate(f):
  a,b = c
  for j in range(t+m):
    if j < a or j-a >= t:
      dp[i+1][j] = dp[i][j]
    else:
      dp[i+1][j] = max(dp[i][j],dp[i][j-a]+b)
      
print(max(dp[n]))

Submission status: Accepted

Solution code:
import numpy as np
N, T = map(int, input().split())

menu = []
for _ in range(N):
    m = tuple(map(int, input().split()))
    menu.append(m)
menu = sorted(menu, key=lambda m: m[0])

# 料理i-1をj-1分までに完食するときの満足度最大値
dp = np.zeros((N, T), dtype='int64')
anss = []

for i in range(1, N):
    # 一つまえのメニューについて
    ai, bi = menu[i-1]
    dp[i][:ai] = dp[i-1][:ai]  # 時間が足りないので注文しない
    dp[i][ai:] = np.fmax(
        dp[i-1][ai:], # 何も注文しない
        dp[i-1][:-ai] + bi # 注文した場合, ai分かかっても大丈夫な範囲から取得
    )
    # 加えて自身を最後に食べた場合を記録
    anss.append(dp[i][-1] + menu[i][1])

print(max(anss))

Submission status: Accepted

Solution code:



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


"""
最後に食べる料理は時刻Tを超えても食べていてOKなので、時刻Tの時点で、食べるのに必要な時間が長くても得点の高いものを食べればよい
最後に食べるやつ x N-1品からi番目まで選べる時 x T-1分までのうちt分までに食べ終えて得られる最大のおいしさ
でDPをやると、O(N*N*T)で間に合わない

↑は最後に食べるものを軸に考えたDPだが、実際の所、その後ろの「N-1品～T-1までに食べ終えて得られる最大のおいしさ」を軸にしてみると、
この「」の後に食べる候補で全体の美味しさを最大化できるのは、残りの中で最も美味しいものである。
なので、最後に食べるもののループは実際は必要ない
これでO(N*T)程度になるので間に合う
ただし、食べる時間が速い順に並べおく必要がある。（先にT-1までに食べ終えておくものの中で、最後に食べるのより時間がかかるものがあるなら、入れ替えたほうがよいケースが出てくるので）
"""


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

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

ans = 0

for i in range(N):
    tmp = 0
    if i < N-1:
        for j in range(i+1, N):
            tmp = max(tmp, AB[j][1])

    ans = max(ans, dp[i+1][-1] + tmp)


print(ans)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
table = [[0] * (N + 1) for _ in range(T + 1)]
dish = sorted((tuple(map(int, input().split())) for _ in range(N)), key=lambda t: t[0])
for t in range(T + 1):
    for n in range(N):
        minutes_to_take, deliciousness = dish[n]
        now = table[t][n]
        if t < T:
            table[min(T, t + minutes_to_take)][n + 1] = max(table[min(T, t + minutes_to_take)][n + 1], now + deliciousness)
        if n < N:
            table[t][n + 1] = max(table[t][n + 1], now)
print(table[T][N])

Submission status: Accepted

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

Dp = [0 for _ in range(T+1)]

ab = sorted(ab, key = lambda x: x[0])

for i in range(N):
    for j in range(T-1,-1, -1):
        if j+ab[i][0] <= T-1:
            kari2 = Dp[j] + ab[i][1]
            if  Dp[j+ab[i][0]] < kari2:
                Dp[j+ab[i][0]] = kari2
        else:
            kari2 = Dp[j] +ab[i][1]
            if Dp[T] < kari2:
                Dp[T] = kari2
                
print(max(Dp))

Submission status: Accepted

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

dp = [[0] * (T + 3) for _ in range(N + 3)]
dp[0][0] = 0
for i in range(N):
    for j in range(T):
        if A[i] <= j:
            dp[i + 1][j] = max(dp[i][j], dp[i][j - A[i]] + B[i])
        else:
            dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])

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

Submission status: Accepted

Solution code:
n,t = map(int,input().split())
dishes = []
for i in range(n):
    a,b = map(int,input().split())
    dishes.append((a,b))
dp1 = [[0]*t for _ in range(n+2)]
dp2 = [[0]*t for _ in range(n+2)]
for i in range(n):
    a,b = dishes[i]
    for j in range(t):
        if j-a >= 0:
            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(2,n+2)[::-1]:
    a,b = dishes[i-2]
    for j in range(t):
        if j-a >= 0:
            dp2[i-1][j] = max(dp2[i][j],dp2[i][j-a]+b)
        else:
            dp2[i-1][j] = dp2[i][j]
ans = 0
for i in range(n):
    a,b = dishes[i]
    for j in range(t):
        ans = max(ans,dp1[i][j]+dp2[i+2][t-1-j]+b)
print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import numpy as np

N,T = map(int,readline().split())
m = map(int,read().split())
AB = sorted(zip(m,m))

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)

answer = 0
for i,(a,b) in enumerate(AB):
    np.maximum(dp[a:], dp[:-a] + b, out = dp[a:])
    x = dp.max() + can_add[i]
    if answer < x:
        answer = x

print(answer)

Submission status: Accepted

Solution code:
n,t = map(int,input().split())
orders = []
for i in range(n):
    a,b = map(int,input().split())
    orders.append([a,b])

orders.sort(key=lambda x:(x[0],-x[1]))
# print(orders)

dp = [[-1e10 for i in range(t+1)] for j in range(n+1)]
dp[0][0] = 0

for i,od in enumerate(orders):
    for j in range(t+1):
        dp[i+1][j] = dp[i][j]
    for j in range(t):
        nt = j+od[0]
        if nt > t-1:
            nt = t
        if dp[i+1][nt] < dp[i][j]+od[1]:
            dp[i+1][nt] = dp[i][j]+od[1]

# for l in dp:
#     print(l[:11])
# print(dp[-1])
print(max(dp[-1]))

Submission status: Accepted

Solution code:
n,t = map(int,input().split())
dp = [[0]*(t) for i in range(n+1)]
ab = [list(map(int,input().split()))for i in range(n)]
ab.sort()
ans = 0
for i in range(n):
    a = ab[i][0]
    b = ab[i][1]
    for j in range(t):
        dp[i+1][j] = max(dp[i+1][j],dp[i][j])
        if j- a >= 0:dp[i+1][j] = max(dp[i+1][j],dp[i][j-a]+b)
    ans = max(ans,dp[i][t-1]+b)

print(ans)

Submission status: Accepted

Solution code:
import numpy as np
 
N, T = map(int, input().split())
data = []
for i in range(N):
  a, b = map(int, input().split())
  data.append((a,b))
data.sort()
data = np.array(data)

dp = np.zeros(T)
ans = 0
for a, b in data:
    ans = max(ans,dp[-1]+b)
    if a< T:
        newtable = dp[:T-a] + b
        dp[a:] = np.maximum(dp[a:], newtable)

print(int(ans))

Submission status: Accepted

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

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, t = mi()
    eating_cost = [None]    # 1-index
    energy = [None]    # 1-index
    for _ in range(n):
        a, b = mi()
        eating_cost.append(a)
        energy.append(b)
    
    # dp_cost_until_i[k][i] = (時間コスト k (0<=k<=t-1) 以下で Ai (1<=i<=n) までを使用してエネルギーを最大化した時の値)
    dp_cost_unitl_i = [[0] * (n + 2) for _ in range(t)]
    for time_cost in range(1, t):
        for i in range(1, n + 1):
            tmp = energy[i] + dp_cost_unitl_i[time_cost - eating_cost[i]][i - 1] if time_cost - eating_cost[i] >= 0 else 0
            dp_cost_unitl_i[time_cost][i] = max(dp_cost_unitl_i[time_cost][i - 1], tmp)
    # dp_cost_from_i[k][i] = (時間コスト k (0<=k<=t-1) 以下で Ai (1<=i<=n) からを使用してエネルギーを最大化した時の値)
    dp_cost_from_i = [[0] * (n + 2) for _ in range(t)]
    for time_cost in range(1, t):
        for i in range(n, 0, -1):
            tmp = energy[i] + dp_cost_from_i[time_cost - eating_cost[i]][i + 1] if time_cost - eating_cost[i] >= 0 else 0
            dp_cost_from_i[time_cost][i] = max(dp_cost_from_i[time_cost][i + 1], tmp)
    
    maximum_energy = 0
    for i in range(1, n + 1):
        # Ai が最後に食べるものの時
        for until_i_time in range(t):
            a = dp_cost_unitl_i[until_i_time][i - 1]
            b = dp_cost_from_i[t - 1 - until_i_time][i + 1]
            maximum_energy = max(maximum_energy, energy[i] + a + b)
    
    print(maximum_energy)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math

    #inf = 10**17
    #mod = 10**9 + 7

    n,t = map(int, input().split())
    ab = [list(map(int, input().split())) for _ in range(n)]
    #ab.sort(key=lambda x: x[1])
    ab.sort(key=lambda x: x[0])
    dp = [-1]*(t+1)
    dp[0] = 0
    for a, b in ab:
        for j in range(t-1, -1, -1):
            if dp[j] >= 0:
                if j+a<=t:
                    dp[j+a] = max(dp[j+a], dp[j]+b)
                else:
                    dp[-1] = max(dp[-1], dp[j]+b)
    print(max(dp))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math

    #inf = 10**17
    #mod = 10**9 + 7

    n,t = map(int, input().split())
    ab = [list(map(int, input().split())) for _ in range(n)]
    ab.sort(key=lambda x: x[1])
    ab.sort(key=lambda x: x[0])
    dp = [-1]*(t+1)
    dp[0] = 0
    for a, b in ab:
        for j in range(t-1, -1, -1):
            if dp[j] >= 0:
                if j+a<=t:
                    dp[j+a] = max(dp[j+a], dp[j]+b)
                else:
                    dp[-1] = max(dp[-1], dp[j]+b)
    print(max(dp))

if __name__ == '__main__':
    main()

Submission status: Accepted

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

#(美味しさ,頼まなかったやつの美味しさ最大値)
dp=[(-10**9,-10**9)]*t
dp[0]=(0,0)

for _ in reversed(sorted(info)):
    good,time=_
    for i in range(t-1,-1,-1):
        g0,m0=dp[i]
        dp[i]=(g0,max(m0,good))
        if i>=time:
            g1,m1=dp[i-time]
            if g0+m0<g1+good+m1:
                dp[i]=(g1+good,m1)
ans=0
for a,b in dp:
    ans=max(ans,a+b)

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])
dp1 = [[0 for i in range(t)] for i in range(n+1)]
dp2 = [[0 for i in range(t)] for i in range(n+1)]
for i in range(n):
    a = L[i][0]
    b = L[i][1]
    for j in range(t):
        if j-a >= 0:
            dp1[i+1][j] = max(dp1[i][j], dp1[i][j-a]+b, dp1[i+1][j])
        else:
            dp1[i+1][j] = max(dp1[i][j],dp1[i+1][j])
for i in range(n):
    a = L[n-i-1][0]
    b = L[n-i-1][1]
    if i == 0:
        for j in range(a, t):
            dp2[n-i-1][j] = b
    else:
        for j in range(t):
            if j-a >= 0:
                dp2[n-i-1][j] = max(dp2[n-i][j], dp2[n-i][j-a]+b,dp2[n-i-1][j])
            else:
                dp2[n-i-1][j] = max(dp2[n-i-1][j], dp2[n-i][j])
ans = 0
for i in range(1,n+1):
    for j in range(t):
        ans = max(ans, dp1[i-1][j]+dp2[i][t-1-j]+L[i-1][1])
print(ans)

Submission status: Accepted

Solution code:
n,t = map(int,input().split())
ab = [list(map(int, input().split())) for i in range(n)]
ab.sort()
dp = [[0 for i in range(t+1)]for j in range(n+1)]

for i in range(n):
    ti,vi = ab[i]
    for j in range(t+1):
        if j + ti <= t:
            dp[i+1][j+ti] = max(dp[i+1][j+ti],dp[i][j]+vi)
        dp[i+1][j] = max(dp[i][j],dp[i+1][j])

ma = 0
for i,(ti,vi) in enumerate(ab):
    ma = max(ma,dp[i][t-1]+vi)
print(ma)

Submission status: Accepted

Solution code:
n,t = map(int,input().split())
ab = sorted([list(map(int, input().split())) for i in range(n)])
dp = [[0 for i in range(t+1)]for j in range(n+1)]

for i in range(n):
    ti,vi = ab[i]
    for j in range(t+1):
        if j + ti <= t:
            dp[i+1][j+ti] = max(dp[i+1][j+ti],dp[i][j]+vi)
        dp[i+1][j] = max(dp[i][j],dp[i+1][j])

ans = 0
for i, (ti, vi) in enumerate(ab):
    ans = max(ans, dp[i][t - 1] + vi)
print(ans)

Submission status: Accepted

Solution code:
N, W = map(int, input().split())
items = sorted([list(map(int, input().split())) for i in range(N)])

dp = [[0] * (W + 1) for i in range(N + 1)]

# dpテーブルを埋める
for i in range(N):
    wi, vi = items[i]
    for j in range(W + 1):
        if j + wi <= W:
            dp[i + 1][j + wi] = max(dp[i + 1][j + wi], dp[i][j] + vi)
        dp[i + 1][j] = max(dp[i][j], dp[i + 1][j])


ans = 0
# 最後に入れる商品は、残り容量１の時に入れるとしてしまってよい
for i, (wi, vi) in enumerate(items):
    ans = max(ans, dp[i][W - 1] + vi)

print(ans)

Submission status: Accepted

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

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

# n-1品目までで、t-1分までで達成できる美味しさ計算
dp = [[0]*t for i in range(n)]
for i in range(1,n):
    a,b = x[i-1]
    for j in range(1,t):
        if j-a>=0:
            dp[i][j] = max(dp[i-1][j-a]+b, dp[i][j-1], dp[i-1][j])
        else:
            dp[i][j] = max(dp[i][j-1], dp[i-1][j])

# 最後に一番時間かかるの食べるときの美味しさを計算
ans = 0
for i in range(n):
    ans = max(ans, dp[n-1-i][t-1]+x[-i-1][1])
print(ans)

Submission status: Accepted

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

item=[list(map(int,input().split())) for _ in range(N)]
item = sorted(item,key=lambda x:x[0])

dp=[0]*(T+1)

for a,b in item:
    for t in reversed(range(T)):
        dist=min(T,t+a)
        dp[dist] = max(dp[t]+b,dp[dist])
print(max(dp))

Submission status: Accepted

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

item=[list(map(int,input().split())) for _ in range(N)]
item = sorted(item,key=lambda x:x[0])

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

for i,(a,b) in  enumerate(item,1):
    for t in reversed(range(T)):
        dist=min(T,t+a)
        dp[i][dist] = max(dp[i-1][t]+b,dp[i][dist])
        dp[i][t]=max(dp[i-1][t],dp[i-1][t])
ans=0
for l in dp:
    ans=max(ans,max(l))
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate

n,t = map(int, input().split())
ab = [list(map(int, input().split())) for i in range(n)]
dp1 = [[-(10 ** 18)] * t for i in range(n)]
dp2 = [[-(10 ** 18)] * t for i in range(n)]
dp1[0][0] = 0
dp2[0][0] = 0
for i,(a,b) in enumerate(ab[:-1]):
  for j in range(t):
    dp1[i+1][j] = max(dp1[i+1][j],dp1[i][j])
    if j < t-a:
      dp1[i+1][j+a] = max(dp1[i+1][j+a],dp1[i][j]+b)
for i,(a,b) in enumerate(ab[n-1:0:-1]):
  for j in range(t):
    dp2[i+1][j] = max(dp2[i+1][j],dp2[i][j])
    if j < t-a:
      dp2[i+1][j+a] = max(dp2[i+1][j+a],dp2[i][j]+b)
ans = 0
for key,(i,j,(a,b)) in enumerate(zip(dp1,dp2[::-1],ab)):
  nowi,nowj = 0,0
  I,J = [],[]
  for x,y in zip(i,j):
    nowi = max(nowi,x)
    nowj = max(nowj,y)
    I.append(nowi)
    J.append(nowj)
  J.reverse()
  tmp = 0
  for x,y in zip(I,J):
    tmp = max(tmp,x+y)
  tmp += b
  ans = max(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline   #input高速化 １文字の時の改行文字に注意+

d={i:0 for i in range(3001)}
db={i:0 for i in range(3001)}

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

x=[tuple(map(int,input().split()))for i in n*[0]]
x.sort()
dp=[]
dp2=[]
for time,value in x:
    for k,v in d.copy().items():
        if k+time<t:
            if d[k+time]<v+value:
                d[k+time]=v+value
        else:
            break
    l=[0]
    for i in range(1,t+1):
        if d[i]>l[-1]:
            l.append(d[i])
        else:
            l.append(l[-1])

    dp.append(l)    
        
for time,value in x[::-1]:
    for k,v in db.copy().items():
        if k+time<t:
            if db[k+time]<v+value:
                db[k+time]=v+value
        else:
            break

    l=[0]
    for i in range(1,t+1):
        if db[i]>l[-1]:
            l.append(db[i])
        else:
            l.append(l[-1])
        
    dp2.append(l)
dp=[[0]*t,[0]*t]+dp
dp2=([[0]*t,[0]*t]+dp2)[::-1]

ans=0

for i in range(len(dp)):
    for j in range(t):
        if i==0 or i==len(dp)-1:
            tmp=dp[i][j]+dp2[i][t-j-1]
            if ans<tmp:
                ans=tmp
        else:
            tmp=dp[i][j]+dp2[i][t-j-1]+x[i-1][1]
            if tmp>ans:
                ans=tmp
print(ans)

Submission status: Accepted

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

    dp = [-1] * (T + 3000)
    dp[0] = 0
    for a, b in sorted(AB):
        for i in range(T - 1, -1, -1):
            if dp[i] == -1:
                continue
            if dp[i + a] < dp[i] + b:
                dp[i + a] = dp[i] + b
    print(max(dp))


main()