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

Solution (Python):
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)]
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]
print(max(dp[-1]))

Solution (Python):
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)



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)

Solution (Python):
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]))

Solution (Python):
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)

Solution (Python):
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])

Solution (Python):
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)

Solution (Python):
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])

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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__":
    
    main()

Solution (Python):
import sys
from collections import defaultdict

n, t = map(int, input().split())
knapsack = defaultdict(lambda: 0)
knapsack[0] = 0
tmp_ans = 0
cuisines = [tuple(map(int, line.split())) for line in sys.stdin]
cuisines.sort()
for a, b in cuisines:
    for time, satisfied in list(knapsack.items()):
        if time + a >= t:
            tmp_ans = max(tmp_ans, satisfied + b)
            continue
        knapsack[time + a] = max(knapsack[time + a], satisfied + b)

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

Solution (Python):
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])
        
        
        


print(D[1][-2])

Solution (Python):
def knapsack(n, w, info):
    
    
    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)

Solution (Python):
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()

Solution (Python):

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

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

items.sort()

ans = 0
dp = {0: 0}
for wi, vi in items:
    for w, v in dp.items():
        if w < T:
            v2 = v + vi
            if v2 > ans:
                ans = v2

    for w, v in list(dp.items()):
        w2 = w + wi
        if w2 <= T:
            v2 = v + vi
            if w2 in dp:
                if v2 > dp[w2]:
                    dp[w2] = v2
            else:
                dp[w2] = v2

v2 = max(dp.values())
ans = max(ans, v2)

print(ans)

Solution (Python):
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])

Solution (Python):

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


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



if __name__ == '__main__':
    solve()

Solution (Python):
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)

Solution (Python):

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)
    
    


print(max(dp))

Solution (Python):

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)

Solution (Python):
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7



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

AB.sort()

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

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

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

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

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


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

    return max(r)


print(main())

Solution (Python):
import numpy as np
n,t = map(int, input().split())
DP = np.full((t), -float("inf"))
DP[0] = 0
ans = 0
ab = [list(map(int, input().split())) for i in range(n)]
ab.sort()
for a,b in ab:
    ans = max(ans, max(DP)+b)
    if a<t:
        DP[a:] = np.maximum(DP[a:], DP[:-a]+b)

ans = int(ans)
print(ans)

Solution (Python):
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  

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

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