Problem:


Score : 500 points

Problem Statement

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

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

The restaurant has the following rules:

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

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

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

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

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

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

Constraints

2 \leq N \leq 3000

1 \leq T \leq 3000

1 \leq A_i \leq 3000

1 \leq B_i \leq 3000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N T
A_1 B_1
:
A_N B_N

Output

Print the maximum possible happiness Takahashi can achieve.

Sample Input 1

2 60
10 10
100 100

Sample Output 1

110

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

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

Sample Input 2

3 60
10 10
10 20
10 30

Sample Output 2

60

Takahashi can eat all the dishes within 60 minutes.

Sample Input 3

3 60
30 10
30 20
30 30

Sample Output 3

50

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

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

Sample Input 4

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

Sample Output 4

145



Sample input:
2 60
10 10
100 100


Sample output:
110

Submission status: Accepted

Solution code:
def main():
    N, T, *AB = map(int, open(0).read().split())

    dp = [0] * (T + max(AB[::2]))
    for w, v in sorted(zip(*[iter(AB)] * 2)):
        for i in reversed(range(T)):
            if dp[i + w] < dp[i] + v:
                dp[i + w] =  dp[i] + v

    print(max(dp))

main()

Submission status: Accepted

Solution code:
def main():
    N, T, *AB = map(int, open(0).read().split())

    dp = [0] * (T + max(AB[::2]))
    for w, v in sorted(zip(*[iter(AB)] * 2)):
        for i in reversed(range(T)):
            dp[i + w] = max(dp[i + w], dp[i] + v)

    print(max(dp))

main()

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
AB = [tuple(map(int, input().split())) for _ in range(N)]
AB.sort()
A, B = map(list, zip(*AB))

dp = {0: 0}
for i in range(N):
    prev_dp = dp.copy()
    for a in prev_dp.keys():
        if a >= T or (a + A[i] in dp and dp[a + A[i]] >= prev_dp[a] + B[i]):
            continue
        dp[a + A[i]] = prev_dp[a] + B[i]
print(max(dp.values()))

Submission status: Accepted

Solution code:
import numpy as np

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

AB.sort()

ans = 0
dp = [0] * T
dp = np.zeros(T, int)

for a, b in AB:
    ans = max(ans, dp[-1] + b)
    dp[a:] = np.maximum(dp[a:], dp[:-a] + b)
    # for j in reversed(range(a, T)):
    #     dp[j] = max(dp[j], dp[j-a] + b)

print(ans)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]
dp = [[0] * (T+1) for _ in range(N+1)]
AB.sort()
ret = 0
for i in range(1,N+1):
    for j in range(1,T+1):
        if j < AB[i-1][0]:
            dp[i][j] = dp[i-1][j]
        else:
            dp[i][j] = max(dp[i-1][j-AB[i-1][0]] + AB[i-1][1], dp[i-1][j])

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

print(m)

Submission status: Accepted

Solution code:
import sys
import numpy as np

n, t = map(int, input().split())
knapsack = np.zeros(t, dtype=np.int64)
cuisines = [tuple(map(int, line.split())) for line in sys.stdin]
cuisines.sort()
tmp_ans = 0
for a, b in cuisines:
    tmp_ans = max(tmp_ans, knapsack.max() + b)
    knapsack[a:] = np.maximum(knapsack[a:], knapsack[:-a] + b)
print(tmp_ans)

Submission status: Accepted

Solution code:
N, T = [int(s) for s in input().split(' ')]
AB = sorted([tuple(int(s) for s in input().split(' ')) for _ in range(N)])

dp = [0] * T  # remainder max
ans = 0
for a, b in AB:
  for t, v in enumerate(dp):
    if t >= a:
      dp[t - a] = max(dp[t - a], v + b)
    else:
      ans = max(ans, v + b)
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict

n, t = map(int, input().split())
menu = []

for _ in range(n):
    a, b = map(int, input().split())
    menu.append((a, b))

menu = sorted(menu)

dp = defaultdict(int)
dp[0] = 0

score = 0

for a, b in menu:
    for time, utility in list(dp.items()):
        if time + a >= t:
            score = max(score, utility + b)
        else:
            dp[time + a] = max(dp[time + a], utility + b)

print(max(score, max(dp.values())))

Submission status: Accepted

Solution code:
import numpy as np
 
n, t = map(int, input().split())
a = []
b = []

for _ in range(n):
  a_tmp, b_tmp = map(int, input().split())
  a.append(a_tmp)
  b.append(b_tmp)
    
arg = np.argsort(a)
a = np.array(a)[arg]
b = np.array(b)[arg]
dp = np.zeros((n, t), dtype=np.int)
    
for i in range(n - 1):
  dp[i+1, :a[i]] = dp[i, :a[i]]
  dp[i+1, a[i]:] = np.maximum(dp[i, a[i]:], dp[i, :-a[i]] + b[i])
  
print(np.max(dp[:, -1] + b))

Submission status: Accepted

Solution code:
import numpy as np

n, t = map(int, input().split())
a = []
b = []
for _ in range(n):
  a_tmp, b_tmp = map(int, input().split())
  a.append(a_tmp)
  b.append(b_tmp)
arg = np.argsort(a)
a = np.array(a)[arg]
b = np.array(b)[arg]
dp = np.zeros((n, t), dtype=np.int)
for i in range(n - 1):
  dp[i+1, :a[i]] = dp[i, :a[i]]
  dp[i+1, a[i]:] = np.maximum(dp[i, a[i]:], dp[i, :-a[i]] + b[i])
  
print(np.max(dp[:, -1] + b))

Submission status: Accepted

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

import sys
import math
import copy
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,t = LI()
ab = [LI() for _ in range(n)]
dp1 = [0]*t
dp2 = [0]*t
for i in range(n):
    a,b = ab[i]
    for j in range(t)[::-1]:
        if j - a < 0:
            dp2[j] = max(dp2[j],dp1[j]+b)
            continue
        tmp1,tmp2 = dp1[j],dp2[j]
        dp1[j] = max(tmp1,dp1[j-a]+b)
        dp2[j] = max(tmp2,tmp1+b,dp2[j-a]+b)
print(dp2[-1])

Submission status: Accepted

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

n, t = map(int, input().split())
dish = [tuple(map(int, input().split())) for _ in range(n)]
dish.sort()
# print(*dish, sep='\n')

dp = [[0] * (t + 1) for _ in range(n + 1)]
for i in range(n):
    for t0 in range(t):
        dp[i + 1][t0] = dp[i][t0]
    for t0 in range(t):
        t1 = min(t0 + dish[i][0], t)
        dp[i + 1][t1] = max(dp[i + 1][t1], dp[i][t1], dp[i][t0] + dish[i][1])

ans = max(dp[n])
# print(*dp, sep='\n')
# print([dp[i][-1] for i in range(n + 1)])
print(ans)

Submission status: Accepted

Solution code:
# dp[i][t_sum]: i番目までの品物で時間がt_sumを超えないように選んだときの、満足度の総和の最大値
N, T = map(int, input().split())
items = [tuple(map(int, input().split())) for i in range(N)]

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

for i in range(N):
    for t_sum in range(T+1):
        if t_sum-items[i][0] >= 0:
            dp1[i+1][t_sum] = max(dp1[i+1][t_sum], dp1[i]
                                  [t_sum-items[i][0]]+items[i][1])
        dp1[i+1][t_sum] = max(dp1[i+1][t_sum], dp1[i][t_sum])

    for t_sum in range(T+1):
        if t_sum-items[N-1-i][0] >= 0:
            dp2[N-1-i][t_sum] = max(dp2[N-1-i][t_sum], dp2[N-i]
                                    [t_sum-items[N-1-i][0]]+items[N-1-i][1])
        dp2[N-1-i][t_sum] = max(dp2[N-1-i][t_sum], dp2[N-i][t_sum])


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

Submission status: Accepted

Solution code:

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

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


AB.sort()

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, d in enumerate(dp):
    # dp[i][:]にはi-1番目までで最大の満足度が入れられてるから、ABのi以降（使ってないから）で一番大きいのを足す
    mb = 0
    for a,b in AB[i:]:
        mb = max(mb, b)
    ans = max(ans, d[-1] + mb)

print(ans)

Submission status: Accepted

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

import sys
import numpy as np
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(0))

# 後は普通のナップザック
TMAX = 6007
dp = np.zeros((N+1, TMAX), dtype=np.int64)
for i in range(N):
    a, b = AB[i]
    dp[i+1] = dp[i]
    dp[i+1,a:a+T] = np.maximum(dp[i+1,a:a+T], dp[i,:T] + b)
print(dp[N].max())

Submission status: Accepted

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

import sys
import numpy as np
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 = np.zeros((N+1, TMAX), dtype=np.int64)
for i in range(N):
    a, b = AB[i]
    dp[i+1] = dp[i]
    dp[i+1,a:a+T] = np.maximum(dp[i+1,a:a+T], dp[i,:T] + b)
print(dp[N].max())

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

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

lim = t + 3001
values = [0] * lim
for a, b in ls:
    for j in reversed(range(lim - a)):
        if j < t:
            values[j + a] = max(values[j + a], values[j] + b)
print(max(values))

Submission status: Accepted

Solution code:
import sys

import numpy as np

n, t = map(int, input().split())
knapsack = np.zeros(t, dtype=np.int64)
cuisines = [tuple(map(int, line.split())) for line in sys.stdin]
cuisines.sort()
tmp_ans = 0
for a, b in cuisines:
    tmp_ans = max(tmp_ans, knapsack.max() + b)
    knapsack[a:] = np.maximum(knapsack[a:], knapsack[:-a] + b)

print(max(tmp_ans, knapsack.max()))

Submission status: Accepted

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


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

#    [print(d) for d in dp]
    ans = 0
    for i, d in enumerate(dp):
        B = [0]
        for a, b in AB[i:]:
            B.append(b)
        ans = max(ans, max(d) + max(B))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
import sys
from operator import itemgetter

def _ia(): return [ int(x) for x in sys.stdin.readline().strip().split() ]

n,t = _ia()
ab = []
for i in range(n): ab.append(_ia())
ab.sort(key=itemgetter(0))
#
bmax= ab[0][0]
dp = [ [0]*(t) for _ in range(n) ]
for i in range(n-1):
    a,b = ab[i]
    
    prev = dp[i]
    dnew = dp[i+1]
    for atot in range(t):
        if atot>=a: dnew[atot] = max(prev[atot],prev[atot-a]+b)
        else: dnew[atot] = prev[atot]
    #
    bmax = max(bmax,prev[-1]+b)
#
print(max(bmax,dp[-1][-1]+ab[-1][1]))

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:
def main():
	_, t, *L = map(int, open(0).read().split())
	d = [0] * (t + max(L[::2]))
	for w, v in sorted((x, y) for x, y in zip(*[iter(L)] * 2)):
		for i in range(t + w - 1, w - 1, -1):
			if d[i - w] + v > d[i]:
				d[i] = d[i - w] + v
	print(max(d))

if __name__=="__main__":
	main()

#vs after contest

Submission status: Accepted

Solution code:
import numpy as np

N,T = map(int, input().split())
item = [None]*N
for i in range(N):
  w,v = map(int,input().split())
  item[i] = [w,v]
item.sort(key=lambda x:x[0])

dp = np.zeros(T, dtype=int)
ans=0
for i in range(N):
    w,v=item[i]
    ans=max(ans,dp.max()+v)
    dp[w:] = np.maximum(dp[w:], dp[:-w] + v)
print(ans)

Submission status: Accepted

Solution code:
n,t = [int(_) for _ in input().split()]
a = []
for i in range(n):
    a.append([int(_) for _ in input().split()])
a = sorted(a, key=lambda x: x[0])
dp = [[0]*(t+1) for i in range(n)]
for j in range(t+1):
    c = a[0][0]
    v = a[0][1]
    if j >= c:
        dp[0][j] = v
dp[0][-1] = v
for i in range(1, n):
    for j in range(1, t+1):
        if j == t:
            c = 1
        else:
            c = a[i][0]
        v = a[i][1]
        if j - c < 0:
            dp[i][j] = dp[i - 1][j]
        else:
            dp[i][j] = max(dp[i - 1][j - c] + v, dp[i-1][j])
ans = 0
for i in range(n-1, 0, -1):
    v = a[i][1]
    ans = max(dp[i-1][t-1]+v, ans)
print(ans)

Submission status: Accepted

Solution code:
# 嘘解法を書いてしまったので、再提出。

# 最後に選ぶ料理は、食べる料理の中で時間が最もかかるものを食べるとして良い。
# 先に a で昇順ソートしておき、最後に選ぶ料理を i とした時に、
# それよりも時間のかからない料理だけを使って、t-1までに食べ切れるものの中で最も高い満足度を得るという方針。
# 前計算はナップサックDPで。

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

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

a = []
b = []
for ai, bi in ab:
    a.append(ai)
    b.append(bi)

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

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

ans = 0

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

print(ans)

Submission status: Accepted

Solution code:
#
import sys
import math
import numpy as np
import itertools
# いくつか入力
n,t = (int(i) for i in input().split())

# n行の複数列ある数値を二次元配列へ。x[n][?]
ab = [[int(i) for i in input().split()] for i in range(n)]
# 0:weight 1:value

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

dp = np.zeros((n+1,t),int)
dp2 = np.zeros((n+1,t),int)

for i in range(n):
    w = ab[i][0]
    dp[i+1][w:] = np.fmax(dp[i][:-w] + ab[i][1], dp[i][w:])
    dp2[i+1][w:] = np.fmax(dp2[i][:-w] + ab[i][1],dp[i][w:] + ab[i][1], dp2[i][w:])
    dp[i+1][:w] = dp[i][:w]
    dp2[i+1][:w] = np.fmax(dp[i][:w] + ab[i][1], dp2[i][:w])

answer = np.amax(dp2)
print(answer)

Submission status: Accepted

Solution code:
n,t=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]
l.sort()
L=[]
for i in range(n):
    L.append(l[i][1])
dp=[[0]*(t) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(t):
        if 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=[]
for i in range(n):
    ans.append(dp[i][-1]+max(L[i:]))
print(max(ans))

Submission status: Accepted

Solution code:
n,t=map(int,input().split())
ab=[tuple(map(int,input().split())) for _ in range(n)]
ab.sort(key=lambda x:x[0])
ab.insert(0,(0,0))
dp=[[0]*t for _ in range(n+1)]
for i in range(1,n+1):
    a,b=ab[i]
    if a<t:
        dp[i][a]=max(dp[i-1][a],b)
    for j in range(t):
        if dp[i-1][j]==0:
            continue
        if j+a<t:
            dp[i][j+a]=max(dp[i][j+a],dp[i-1][j]+b)
        dp[i][j]=max(dp[i-1][j],dp[i][j])
ans=0
p=[j for i,j in ab]
for i in range(1,n):
    ans=max(ans,max(dp[i])+max(p[i+1:]))
ans=max(ans,max(dp[n]))
print(ans)

Submission status: Accepted

Solution code:
n,t=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]
l.sort()
dp=[[0]*(t) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(t):
        if 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=[]
for i in range(n):
    ans.append(dp[i][-1]+l[i][1])
#print(dp)
print(max(ans))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def knapsack2(N,W,weight,value,WW):
  #初期化
  inf=float("inf")
  dp=[[-inf for i in range(WW)] for j in range(N+1)]
  for i in range(WW):
      dp[0][i]=0
  maxval = 0
  #DP
  for i in range(N):
    for w in range(WW):
      if weight[i]<=w:
        if w-weight[i]>=W: #時間切れ
          dp[i+1][w]=dp[i][w]
        else: #注文可能
          dp[i+1][w]=max(dp[i][w-weight[i]]+value[i], dp[i][w])
      else: #NG
        dp[i+1][w]=dp[i][w]
    maxval = max([maxval, max(dp[i+1])])
  return maxval
 
N, T = map(int,input().split())
WW = T+3000
ab = []
for i in range(N):
    ab.append(tuple(map(int,input().split())))
ab =  sorted(ab,key=lambda x:x[0])
weight = [elem[0] for elem in ab]
value = [elem[1] for elem in ab]
res = knapsack2(N,T,weight,value,WW)
print(res)

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod2 = 998244353
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n,w = inpl()
wv = [inpl() for i in range(n)]
dp = [[0 for i in range(w+1)] for j in range(n+1)]
wv.sort()
wv.sort(key=lambda x:x[1])
ww = [0] * n
vv = [0] * n
for i in range(n):
    ww[i],vv[i] = wv[i][0], wv[i][1]
for i in range(n-1):
    for j in range(w+1):
        if j >= ww[i]:
            dp[i+1][j] = max(dp[i][j], dp[i][j-ww[i]]+vv[i])
        else:
            dp[i+1][j] = dp[i][j]
res = dp[n-1][w-1]+wv[n-1][1]

dp = [[0 for i in range(w+1)] for j in range(n+1)]
ww[-1],ww[-2] = ww[-2],ww[-1]
vv[-1],vv[-2] = vv[-2],vv[-1]
for i in range(n-1):
    for j in range(w+1):
        if j >= ww[i]:
            dp[i+1][j] = max(dp[i][j], dp[i][j-ww[i]]+vv[i])
        else:
            dp[i+1][j] = dp[i][j]
print(max(res,dp[n-1][w-1]+vv[n-1]))

Submission status: Accepted

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

import numpy as np
d=sorted(d,key=lambda x:x[0])
dp=np.zeros(T,dtype=int)
ans=0
for i in range(len(d)):
  t=d[i][0]
  v=d[i][1]
  ans=max(ans,dp.max()+v)
  np.maximum(dp[:-t]+v,dp[t:],out=dp[t:])

print(ans)

Submission status: Accepted

Solution code:
import sys
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
dp_total = [0]*T
for n in range(N):
    dp_intime_prev, dp_intime = dp_intime, [0]*T
    dp_total_prev, dp_total = dp_total, [0]*T
    for t in range(T):
        if A[n] > t:
            dp_intime[t] = dp_intime_prev[t]
            dp_total[t] = max(B[n]+dp_intime_prev[t], dp_total_prev[t])
        else:
            dp_intime[t] = max(dp_intime_prev[t], B[n]+dp_intime_prev[t-A[n]])
            dp_total[t] = max(B[n]+dp_intime_prev[t],
                              B[n]+dp_total_prev[t-A[n]],
                              dp_total_prev[t])
print(dp_total[-1])

Submission status: Accepted

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

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

a = []
b = []
for ai, bi in ab:
    a.append(ai)
    b.append(bi)

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

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

ans = 0

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

print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
import bisect
from heapq import heappush, heappop

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, T = MAP()
wv = [LIST() for _ in range(N)]
dp1 = [[0]*T for _ in range(N+1)]
dp2 = [[0]*T for _ in range(N+1)]


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

wv = wv[::-1]

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

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

print(ans)

Submission status: Accepted

Solution code:
n,t=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]
l.sort()
dp=[[0]*(t) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(t):
        if 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=[]
for i in range(n):
    ans.append(dp[i][-1]+l[i][1])
print(max(ans))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N, T = map(int, input().split())
D = []
for _ in range(N):
    a, b = map(int, input().split())
    D.append((a,-b))

D.sort()

dp = [[0] * (T) for _ in range(N)]
for i in range(1, N):
    a, b = D[i-1]
    b = -b
    for t in range(T):
        dp[i][t] = dp[i-1][t]
        if t >= a:
            dp[i][t] = max(dp[i][t], dp[i-1][t-a]+b)

print(max(-D[i][1] + dp[i][-1] for i in range(1,N)))

Submission status: Accepted

Solution code:
import sys
import numpy as np
read = sys.stdin.read

N, T, *AB = map(int, read().split())
AB = np.array(AB).reshape(N, 2)
AB = AB[np.argsort(AB[:, 0], axis=0)]

dp = np.zeros(T, np.int64)
answer = []

for a, b in AB:
    answer.append(dp[-1] + b)
    if a > T:
        continue

    dp[a:] = np.maximum(dp[:T - a] + b, dp[a:])

print(max(answer))

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)]
    AB.sort()

    dp=[0]*T
    ans=-INF
    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
    print(ans)
resolve()

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)]
    AB.sort()

    dp=[0]*T
    ans=-INF
    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
    print(max(ans,max(dp)))
resolve()

Submission status: Accepted

Solution code:
import sys
import numpy as np
read = sys.stdin.read

N, T, *AB = map(int, read().split())
AB = np.array(AB).reshape(N, 2)
AB = AB[np.argsort(AB[:, 0], axis=0)]

dp = np.zeros(T, np.int64)
answer = []

for a, b in AB:
    answer.append(dp[-1] + b)
    if a > T:
        continue

    dp[a:] = np.maximum(dp[:T - a] + b, dp[a:])

answer.append(dp.max())
print(max(answer))

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
dishes = [tuple(map(int, input().split())) for _ in range(N)]
dishes = sorted(dishes)
dp = [[-1 for j in range(T+3001)] for i in range(N+1)]
for i in range(N+1):
    dp[i][0] = 0
for i in range(N):
    a, b = dishes[i]
    for j in range(T+3001):
        if j < a or T + a <= j:
            dp[i+1][j] = dp[i][j]
        else:
            if dp[i][j-a] < 0:
                dp[i+1][j] = dp[i][j]
            else:
                dp[i+1][j] = max(dp[i][j], dp[i][j - a] + b)
print(max(dp[-1]))

Submission status: Accepted

Solution code:
import collections

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

dp = [[0] * (t + 1) for _ in range(n + 1)]
for i in range(n):
    for j in range(t):
        dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
        k = min(t, j + a[i])
        dp[i + 1][k] = max(dp[i + 1][k], dp[i][j] + b[i])
print(max(map(max, dp)))

Submission status: Accepted

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

ab = []

for i in range(n):
    ab_ = [int(_) for _ in input().split()]
    ab.append(ab_)

ab.sort()

dp = [-1 for _ in range(6000)]
dp[0] = 0
dp2 = dp[:]


dplist = [0]

for i in range(n):

    dp_trans = ab[i][0]
    dp_delicious = ab[i][1]

    for j in range(t):
        if dp[j] != -1:
            dp2[j+dp_trans] = max(dp[j+dp_trans], dp[j] + dp_delicious)
    dp = dp2[:]

print(max(dp))

Submission status: Accepted

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

n,t = m()

li = [l() for i in range(n)]

ma = []
for i in range(n):
    ma.append([li[i][1],i])

ma.sort(reverse = True)

li.sort(key = lambda x:x[0])

dp = [0 for i in range(t + 3000)]

for i in range(n):
    for k in range(li[i][0]+t-1,li[i][0]-1,-1):
        if dp[k] <= dp[k-li[i][0]] + li[i][1]:
            dp[k] = dp[k-li[i][0]] + li[i][1]


dp.sort(reverse = True)
ans = dp[0]

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

a = []
b = []
for ai, bi in ab:
    a.append(ai)
    b.append(bi)

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

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

happy = dp[n][t-1]
i = n
j = t-1


used = set([])
while i > 0 or j > 0:
    pi, pj = prev[i][j]
    if dp[pi][pj] != dp[i][j]:
        used.add(pi)
    i = pi
    j = pj

unused = []
for i in range(n):
    if i not in used:
        unused.append(b[i])

if len(unused) == 0:
    ans = happy
else:
    ans = happy + max(unused)

print(ans)

Submission status: Accepted

Solution code:
def MAP(): return list(map(int,input().split()))
def INT(): return int(input())
def FLOAT(): return float(input())
MOD = 10**9+7

n,t = MAP()
dp = [0] * 6005
ab = []
for i in range(n):
    ab.append(MAP())

ab.sort(key=lambda x: x[0])
for u in ab:
    for i in range(6004-u[0], -1, -1):
        if i < t:
            dp[i+u[0]] = max(dp[i+u[0]], dp[i] + u[1])
print(max(dp))