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 main():
    n,t=map(int,input().split())
    AB=[list(map(int,input().split())) for _ in range(n)]
    AB.sort(key=lambda x: (x[0],-x[1]))
    DP=[[0]*(6001) for _ in range(n+1)]
    for i,(a,b) in enumerate(AB):
        for j in range(1,6001):
            if j<a:
                DP[i+1][j]=max(DP[i][j],DP[i+1][j-1])
            elif j-a<t:
                DP[i+1][j]=max(DP[i][j],DP[i+1][j-1],DP[i][j-a]+b)
            else:
                DP[i+1][j]=max(DP[i][j],DP[i+1][j-1])
    print(max(DP[-1]))
    
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:

import sys
def input():
	return sys.stdin.readline().strip()



N, T = list(map(int, input().split()))

AB = []
for i in range(N):
	AB.append(tuple(map(int, input().split())))
AB.sort(reverse=True)

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

max_under = 0
for i in range(N):
	max_under = max(max_under, AB[i][1])
	dp[0][i] = max_under

for t in range(T):
	dp[t][0] = AB[0][1]

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


print(dp[-1][-1])

Submission status: Accepted

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

N, T = map(int, input().split())
d = []
for _ in range(N):
  d.append(list(map(int, input().split())))
d.sort(key = lambda x: x[0])
dp = [[0] * (T + 1) for _ in range(N + 1)]
res = 0
for i in range(N):
  for j in range(T):
    dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
    if j + d[i][0] <= T: dp[i + 1][j + d[i][0]] = max(dp[i + 1][j + d[i][0]], dp[i][j] + d[i][1])
    else: dp[i + 1][T] = max(dp[i + 1][T], dp[i][j] + d[i][1])
  #print(dp[i])
for i in range(N + 1):
  res = max(max(dp[i]), res)
print(res)

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=[[-1]*t for i in range(n)]
for i in range(n):
    dp[i][0]=0
a,b=ab[0]
if a<t:
    dp[0][a]=b
for i in range(1,n):
    a,b=ab[i]
    for j in range(min(a,t)):
        dp[i][j]=dp[i-1][j]
    for j in range(a,t):
        if dp[i-1][j-a]==-1:
            dp[i][j]=dp[i-1][j]
        else:
            dp[i][j]=max(dp[i-1][j],dp[i-1][j-a]+b)
table=[0]*n
table[n-1]=ab[n-1][1]
for i in range(n-2,-1,-1):
    table[i]=max(table[i+1],ab[i][1])
ans=0
for i in range(n-1):
    c=max(dp[i])
    ans=max(ans,c+table[i+1])
print(ans)

Submission status: Accepted

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] = dp[i][t]
        if t-a>=0:
            dp[i+1][t] = max(dp[i+1][t],dp[i][t-a]+b)

s = []
t = T-1
for j in range(N-1,-1,-1):
    a,b = AB[j]
    while (dp[j+1][t] == dp[j+1][t-1]) and t>0:
        t -= 1
    if dp[j+1][t] == dp[j][t]:
        pass
    else:
        t -= a
        s.append(j)

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

Submission status: Accepted

Solution code:

N,T = map(int,input().split())

tlis = [[0] * (T+1) for i in range(N+1)]
AB = []

for i in range(N):

    A,B = map(int,input().split())
    AB.append([A,B])

AB.sort()

for i in range(N):

    A = AB[i][0]
    B = AB[i][1]

    for j in range(T+1):

        tlis[i+1][j] = tlis[i][j]

    tlis[i+1][min(T,A)] = max(tlis[i+1][min(T,A)],B)
    
    for j in range(T):

        if tlis[i][j] != 0:
            tlis[i+1][ min(T , j+A) ] = max(tlis[i+1][ min(T , j+A) ] , tlis[i][j] + B)
    

    
ans = 0
for i in range(T+1):

    ans = max(ans , tlis[-1][i])
    
print (ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
N, T = inpl()
A = [None]*N
B = [None]*N
for i in range(N):
    A[i], B[i] = inpl()

dp_intime = [[0]*T for _ in range(N+1)]
dp_total = [[0]*T for _ in range(N+1)]
for n in range(1,N+1):
    for t in range(T):
        if A[n-1] > t:
            dp_intime[n][t] = dp_intime[n-1][t]
            dp_total[n][t] = max(B[n-1]+dp_intime[n-1][t], dp_total[n-1][t])
        else:
            dp_intime[n][t] = max(dp_intime[n-1][t], B[n-1]+dp_intime[n-1][t-A[n-1]])
            dp_total[n][t] = max(B[n-1]+dp_intime[n-1][t],
                                 B[n-1]+dp_total[n-1][t-A[n-1]],
                                 dp_total[n-1][t])
print(dp_total[-1][-1])

Submission status: Accepted

Solution code:
n,t = map(int,input().split())
time = [0 for i in range(3000)]
now = 0
ans = 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 lis[i][0] + j >= t:
            ans = max(ans,time[j]+lis[i][1])
        else:
            time[j+lis[i][0]] = max(time[j+lis[i][0]],time[j]+lis[i][1])
print(max(ans,max(time)))

Submission status: Accepted

Solution code:
import sys
n,t = map(int, input().split())
a = []
b = []
m = []
for i in range(n):
    ai,bi = map(int, input().split())
    m.append((ai,bi))
m.sort()
###ソート
for i in range(n):
    a.append(m[i][0])
    b.append(m[i][1])
a_mx = max(a)
dp = [0]*(t+a_mx+1)
#dp2 = [i for i in range(t+a_mx)]##注文時間

for i in range(n):
    for s in range(t+a[i]-1,a[i]-1,-1):##時間制限
        if dp[s]<=dp[s-a[i]]+b[i]:
            dp[s] = dp[s-a[i]]+b[i]
#            dp2[s] = s-a[i]


        
print(max(dp))

Submission status: Accepted

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

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

for i, (ai, bi) in enumerate(ab):
    for ti in range(t):
        if ti + ai < t:
            dp[i+1][ti + ai] = max(dp[i][ti + ai], dp[i][ti] + bi)
        dp[i+1][ti] = max(dp[i+1][ti], dp[i][ti])

# 経路復元
chose = set()
maxtime = dp[n].index(max(dp[n]))

for idx in range(n, 0, -1):
    if dp[idx][maxtime] != dp[idx-1][maxtime]:
        chose.add(idx-1)
        maxtime -= ab[idx-1][0]

allitem = set(range(n))
notchose = allitem - chose

notchosemax = 0
if notchose:
    for i in notchose:
        notchosemax = max(notchosemax, ab[i][1])

print(max(dp[n]) + notchosemax)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
T -= 1
Meals = sorted([list(map(int, input().split())) for i in range(N)])
dp = [[0] * (T + 1) for i in range(N + 1)]
prev = [[-1] * (T + 1) for i in range(N + 1)]


for i, (cost, value) in enumerate(Meals):
    for j in range(T + 1):
        if j >= cost:
            if dp[i + 1][j] <= dp[i][j - cost] + value:
                dp[i + 1][j] = dp[i][j - cost] + value
                prev[i + 1][j] = j - cost

        if dp[i + 1][j] <= dp[i][j]:
            dp[i + 1][j] = dp[i][j]
            prev[i + 1][j] = j

# 復元
selected = set()
cur_w = T
for i in range(N - 1, -1, -1):
    if prev[i + 1][cur_w] == cur_w - Meals[i][0]:
        selected.add(i)
    cur_w = prev[i + 1][cur_w]

non_selected = set(list(range(N))) - selected
ans = dp[N][T]
add = 0
for ni in non_selected:
    add = max(add, Meals[ni][1])

print(dp[N][T] + add)

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]*(T+3001) for i in range(N+1)]
for i in range(1,N+1):
    a,b=AB[i-1]
    for j in range(T+3001):
        dp[i][j]=dp[i-1][j]
        if 0<=j-a<T:
            dp[i][j]=max(dp[i][j],dp[i-1][j-a]+b)
print(max(dp[-1]))

Submission status: Accepted

Solution code:
def main():
    N, T = map(int, input().split())
    A = [0] * N
    B = [0] * N
    X = [list(map(int, input().split())) for _ in range(N)]
    X.sort(lambda x: x[0])
    for i in range(N):
        A[i], B[i] = X[i]
    M = T+max(A)
    dp = [[(0, 0)] * M for _ in range(2)]
    for i in range(N):
        a, b = A[i], B[i]
        for j in range(M):
            dp[i & 1][j] = dp[(i-1) & 1][j]
        for j in range(a, M):
            t, m = dp[(i-1) & 1][j-a]
            t += b
            m = max(m, a)
            if j - m < T and dp[i & 1][j][0] < t:
                dp[i & 1][j] = (t, m)
    ans = 0
    for i in range(M):
        ans = max(ans, dp[(N-1) & 1][i][0])
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

import sys
from operator import itemgetter

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

N, T = MAP()
AB = []
for i in range(N):
    a, b = MAP()
    AB.append((a, b))

AB.sort(key=itemgetter(1), reverse=True)
AB.sort(key=itemgetter(0))

TMAX = 6007
dp = list2d(N+1, TMAX, 0)
for i in range(N):
    a, b = AB[i]
    for j in range(TMAX):
        dp[i+1][j] = max(dp[i+1][j], dp[i][j])
        if j < T:
            dp[i+1][j+a] = max(dp[i+1][j+a], dp[i][j] + b)
print(max(dp[N]))

Submission status: Accepted

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:
    newDp = dp[::]
    for t, d in enumerate(dp[:T]):
        newDp[min(T, t + a)] = max(newDp[min(T, t + a)], d + b)
    dp = newDp

print(max(dp))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(500000)

def knapsack(VW, limit):
    n = len(VW)
    dp = [[0] * (limit+1) for _ in range(n+1)]
    for idx, (v, w) in enumerate(VW, 1):
        for we in range(limit+1):
            dp[idx][we] = dp[idx-1][we]
            if we >= w:
                dp[idx][we] = max(dp[idx][we], dp[idx-1][we-w]+v)
    return dp

def main():
    N, T = map(int, input().split())
    VW = []
    ma = 0
    ama = -1
    for i in range(N):
        w, v = map(int, input().split())
        if ma < v:
            ma = v
            ama = i
        VW.append([v, w])
    dp1 = knapsack(VW, T-1)
    VW.reverse()
    dp2 = knapsack(VW, T-1)
    dp2.reverse()
    VW.reverse()
    #for d in dp2:
    #    print(d)
    ans = 0
    for (v, w), d1, d2 in zip(VW, dp1[:-1], dp2[1:]):
        #print(v, w, d1, d2)
        for i in range(1, T):
            d1[i] = max(d1[i], d1[i-1])
            d2[i] = max(d2[i], d2[i-1])
        for dd1, dd2 in zip(d1, d2[::-1]):
            ans = max(ans, dd1+dd2+v)
    print(ans)


main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,T=map(int,input().split())
    AB=[tuple(map(int,input().split())) for _ in range(n)]
    ans=-INF

    # 何も考えずやる
    dp=[0]*T
    for i in range(n):
        a,b=AB[i]
        ndp=dp[:]
        for t in range(T):
            if(t+a<T):
                ndp[t+a]=max(ndp[t+a],dp[t]+b)
            else:
                ans=max(ans,dp[t]+b)
        dp=ndp
    ans=max(ans,max(dp))

    # 時間が最もかかるもののうち、価値が最大のものを最後にする
    AB.sort()
    la,lb=AB[-1]

    dp=[0]*T
    for i in range(n-1):
        a,b=AB[i]
        ndp=dp[:]
        for t in range(T):
            if(t+a<T):
                ndp[t+a]=max(ndp[t+a],dp[t]+b)
            else:
                ans=max(ans,dp[t]+b)
        dp=ndp
    ans=max(ans,max(dp)+lb)

    # 価値が最大のもののうち、時間が最もかかるものを最後にする
    AB.sort(lambda x:(x[1],x[0]))
    la,lb=AB[-1]

    dp=[0]*T
    for i in range(n-1):
        a,b=AB[i]
        ndp=dp[:]
        for t in range(T):
            if(t+a<T):
                ndp[t+a]=max(ndp[t+a],dp[t]+b)
            else:
                ans=max(ans,dp[t]+b)
        dp=ndp
    ans=max(ans,max(dp)+lb)

    print(ans)
resolve()

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:
N, T = map(int, input().split())

items = []
for i in range(N):
	a, b = map(int, input().split())
	items.append((a, -b))

items.sort()

scores = [None] * T
scores[0] = 0
max_d = 0

def search_max():
	max = 0
	for i in range(T):
		s = scores[i]
		if s != None and s > max:
			max = s
	return max

for i in range(N):
	a, b = items[i]
	b = -b
	d = search_max() + b
	if d > max_d:
		max_d = d
	for j in range(T - 1, -1, -1):
		s = scores[j]
		if s != None:
			s += b
			t = j + a
			if t < T:
				prev_s = scores[t]
				if prev_s == None or prev_s < s:
					scores[t] = s

print(max_d)

Submission status: Accepted

Solution code:
dp = [[-1 for i in range(6005)] for j in range(6005)]


def f(idx, time):
    if time >= T:
        return 0
    if idx >= N:
        return 0
    if dp[idx][time] != -1:
        return dp[idx][time]
    dp[idx][time] = max(f(idx+1, time), B[idx]+f(idx+1, time+A[idx]))
    return dp[idx][time]

N, T = [int(i) for i in input().split()]
data = []
A, B = [], []

for i in range(N):
    a, b = [int(j) for j in input().split()]
    data.append([a,b])
    A.append(a)
    B.append(b)

data.sort()
A, B = [], []
for i, j in data:
    A.append(i)
    B.append(j)

for idx in range(N, -1, -1):
    for time in range(T, -1, -1):
        if time == T:
            dp[idx][time] = 0
            continue
        if idx == N:
            dp[idx][time] = 0
            continue
        if A[idx]+time >= T:
            fval = 0
        else:
            fval = dp[idx+1][time+A[idx]]
        dp[idx][time] = max(dp[idx+1][time], B[idx] + fval)

print(dp[0][0])

Submission status: Accepted

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

n,t = map(int,input().split())
dg = 10**5

ab = []
tank = -1

for i in range(n):
    a,b = map(int,input().split())
    if a >= t:
        tank = max(tank,b)
    else:
        ab.append(b*dg+a)
ab.sort()

n = len(ab)

#print(ab)

if len(ab) == 0:
    print(tank)
    exit()

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

for i in range(n):
    a,b = ab[i]%dg,ab[i]//dg
    for j in range(min(a,t+1)):
        dp[i][j] = dp[i-1][j]
    for j in range(a,t+1):
        dp[i][j] = max(dp[i-1][j],dp[i-1][j-a]+b)

if len(ab) == 1:
    a,b = ab[0]%dg,ab[0]//dg
    print(b+tank)
    exit()

res = dp[n-1][t]

if tank > 0:
    res = max(res,dp[n-1][t-1]+tank)


p = 0
q = 0
for k in range(n-1,0,-1):
    a,b = ab[k]%dg,ab[k]//dg
    q += b
    res = max(res,q+dp[k-1][t-p-1])
    p += a
    if p >= t:
        break
print(res)

Submission status: Accepted

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


AB.sort(reverse = True)
DP = [[0] * T for _ in range(N)]
DP[0][0] = AB[0][1]
for i in range(1, N):
  a, b = AB[i]
  DP[i][0] = max(DP[i - 1][0], b)
  for j in range(T):
    DP[i][j] = max(DP[i][j], DP[i - 1][j])
    if j + a < T:
      DP[i][j + a] = DP[i - 1][j] + b

print(max(DP[-1]))

Submission status: Accepted

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

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

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

max_sum = 0
max_t = 0
for t in range(T):
    if dp[-1][t] > max_sum:
        max_sum = dp[-1][t]
        max_t = t

cur_T = max_t
used = [0] * N
for i in range(N, 0, -1):
    if prev[i][cur_T] == cur_T - food[i-1][0]:
        cur_T -= food[i-1][0]
        used[i-1] = 1

max_b = 0
for i in range(N):
    if used[i] == 0:
        max_b = max(max_b, food[i][1])

print(max_sum + max_b)

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

N,T = II()
A,B = Line(N,2)

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

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

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

print(m2[N-1][T])

Submission status: Accepted

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)]


def knapsack_01(items, weight_limit):
    values = [0] * (weight_limit + 1)
    for w, v in items:
        for j in reversed(range(w, weight_limit + 1)):
            values[j] = max(values[j], values[j - w] + v)
    return max(values)


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

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

val = dp[n][t - 1]

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

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

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
food1 = []
for _ in range(N):
    a, b = map(int, input().split())
    food1.append((a, b))
dp1 = [[0]*T for _ in range(N+1)]
dp2 = [[0]*T for _ in range(N+1)]
food2 = food1[::-1]
for i in range(N):
    a1, b1 = food1[i]
    a2, b2 = food2[i]
    for t in range(T):
        dp1[i+1][t] = max(dp1[i+1][t], dp1[i][t])
        if t+a1<T:
            dp1[i+1][t+a1] = max(dp1[i+1][t+a1], dp1[i][t]+b1)
        dp2[i+1][t] = max(dp2[i+1][t], dp2[i][t])
        if t+a2<T:
            dp2[i+1][t+a2] = max(dp2[i+1][t+a2], dp2[i][t]+b2)
ans = 0
for i in range(N):
    res = max(food1[i][1]+dp1[i][t]+dp2[N-i-1][T-t-1] for t in range(T))
    ans = max(ans, res)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

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

for i in range(N):
    for j in range(T):
        if j < L[i][0]:
            dp[i+1][j] = dp[i][j]
        else:
            dp[i+1][j] = max(dp[i][j], dp[i][j-L[i][0]]+L[i][1])
            
used = []
B = dp[N][T-1]
j = T-1
for i in range(N-1, -1, -1):
    if B == dp[i][j]:
        continue
    B -= L[i][1]
    used.append(i)
    j -= L[i][0]
        
ans = dp[N][T-1]
c = 0
for i in range(N):
    if i in used:
        continue
    c = max(c, L[i][1])
    
print(ans+c)

Submission status: Accepted

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

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

D = [[0] * (t+1) for i in range(2)]

for i in range(n):
    for j in range(t, -1, -1):
        D[1][j] = max(D[1][j], D[0][j] + A[i][1])
        if j-A[i][0] >= 0:
            
            D[0][j] = max(D[0][j], D[0][j-A[i][0]] + A[i][1])
            D[1][j] = max(D[1][j], D[1][j-A[i][0]] + A[i][1])
        # else:
        #     # print(D)
        #     break

# print(D)
print(D[1][-2])

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

Submission status: Accepted

Solution code:
#設定
import sys
input = sys.stdin.buffer.readline

#ライブラリインポート
from collections import defaultdict

#入力受け取り
def getlist():
	return list(map(int, input().split()))


#処理内容
def main():
	N, T = getlist()
	K = []
	for i in range(N):
		A, B = getlist()
		K.append([A, B])
	DP = [[0 for i in range(T)] for j in range(N + 1)]
	for i in range(N):
		W, V = K[i][0], K[i][1]
		for j in range(T):
			if j < W:
				DP[i + 1][j] = DP[i][j]
			else:
				DP[i + 1][j] = max(DP[i][j], DP[i][j - W] + V)
	ans = DP[-1][-1]
	use = [0] * N
	Y = T - 1
	for i in range(N):
		if DP[N - i][Y] != DP[N - i - 1][Y]:
			use[N - 1 - i] = 1
			Y -= K[-1 - i][0]
	lis = []
	for i in range(N):
		if use[i] == 0:
			lis.append(K[i][1])
	lis = sorted(lis)
	if len(lis) >= 1:
		ans += lis[-1]
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Accepted

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

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

q = 0
for i in range(1,n+1):
    q = max(q,data[i-1][0])
    dp2[1][i] = q

for i in range(1,t+1):
    for j in range(1,n+1):
        if i-data[j-1][0] >= 0:
            dp1[i][j] = max(dp1[i][j-1],dp1[i-data[j-1][0]][j-1]+data[j-1][1])
            dp2[i][j] = max(dp2[i][j-1],dp2[i-data[j-1][0]][j-1]+data[j-1][1],dp1[i-1][j-1]+data[j-1][1])
        else:
            dp1[i][j] = dp1[i][j-1]
            dp2[i][j] = max(dp2[i][j-1],dp1[i-1][j-1]+data[j-1][1])


print(dp2[t][n])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#solve
def solve():
    n, t = LI()
    ab = LIR(n)
    ab.sort(key=lambda x: x[0])
    dp = [0] * (t+1)
    for i in range(n):
        a, b = ab[i]
        for ti in range(t - 1, -1, -1):
            dp[min(ti + a, t)] = max(dp[min(ti + a, t)], dp[ti] + b)
    print(dp[t])
    return


#main
if __name__ == '__main__':
    solve()

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].copy() + b, out = dp[a:])
    x = dp.max() + can_add[i]
    if answer < x:
        answer = x

print(answer)

Submission status: Accepted

Solution code:

import numpy as np
import sys
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

N,T = inpl()
dp = np.zeros((6001),int)
ABs = [inpl() for _ in range(N)]
ABs.sort()

for A,B in ABs:
    dp[A:T+A] = np.maximum(dp[A:T+A], dp[:T]+B)
    # for i in reversed(range(A,T+A)):
    #     dp[i] = max(dp[i-A] + B, dp[i])


print(max(dp))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import math
input = sys.stdin.readline
MOD = 10**9 + 7

ab = []
n, t = [int(item) for item in input().split()]
for i in range(n):
    a, b = [int(item) for item in input().split()]
    ab.append((a, b))
ab.sort()

dp = [[-1] * (t+1) for _ in range(n+1)]
dp[0][0] = 0
ans = 0
for i, (a, b) in enumerate(ab):
    for j in range(t-1, -1, -1):
        if dp[i][j] == -1:
            continue
        dp[i+1][j] = max(dp[i+1][j], dp[i][j])
        if a + j >= t:
            ans = max(ans, dp[i][j] + b)
            continue
        dp[i+1][j + a] = max(dp[i][j + a], dp[i][j] + b)
        ans = max(ans, dp[i+1][j + a])

print(ans)