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: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs= sys.stdin.buffer.readlines
#rstrip().decode('utf-8')
#INF=float("inf")
#MOD=10**9+7
#sys.setrecursionlimit(2147483647)
#import math
#import numpy as np
#import operator
#import bisect
#from heapq import heapify,heappop,heappush
#from math import gcd
#from fractions import gcd
#from collections import deque
#from collections import defaultdict
#from collections import Counter
#from itertools import accumulate
#from itertools import groupby
#from itertools import permutations
#from itertools import combinations
#from scipy.sparse import csr_matrix
#from scipy.sparse.csgraph import floyd_warshall
#from scipy.sparse.csgraph import csgraph_from_dense
#from scipy.sparse.csgraph import dijkstra
#map(int,input().split())


# 枝刈り探索（分枝限定法）

class Knapsack:
	def __init__(self, VW):
		self.VW = VW
		self.VW.sort(key=lambda vw: vw[0] / vw[1], reverse=True)
		self.n = len(VW)
	
	def solve(self, capacity, ok=0):
		self.ok = ok
		self.capacity = capacity
		return self._dfs(0, 0, 0)
	
	def _dfs(self, i, v_now, w_now):
		if i == self.n:
			self.ok = max(self.ok, v_now)
			return v_now
		ng, f = self._solve_relaxation(i, self.capacity - w_now)
		ng += v_now
		if f:
			self.ok = max(self.ok, ng)
			return ng
		if ng < self.ok:
			return -float("inf")
		res = -float("inf")
		v, w = self.VW[i]
		if w_now + w <= self.capacity:
			res = max(res, self._dfs(i + 1, v_now + v, w_now + w))
		res = max(res, self._dfs(i + 1, v_now, w_now))
		return res
	
	def _solve_relaxation(self, i, capacity):
		res = 0
		f = True
		for v, w in self.VW[i:]:
			if capacity == 0:
				break
			if w <= capacity:
				capacity -= w
				res += v
			else:
				f = False
				res += v * (capacity / w)
				break
		return res, f

def main():
	n,t=map(int,input().split())
	AB = [list(map(int, input().split())) for _ in range(n)]
	AB.sort(key=lambda x:x[1],reverse=True)
	knapsack = Knapsack(AB)
	ans=knapsack.solve(t-1)+AB[-1][1]
	print(ans)
	
	
	

	
	
if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs= sys.stdin.buffer.readlines
#rstrip().decode('utf-8')
INF=float("inf")
MOD=10**9+7
#sys.setrecursionlimit(2147483647)
#import math
import numpy as np
#import operator
#import bisect
#from heapq import heapify,heappop,heappush
#from math import gcd
#from fractions import gcd
#from collections import deque
#from collections import defaultdict
#from collections import Counter
#from itertools import accumulate
#from itertools import groupby
#from itertools import permutations
#from itertools import combinations
#from scipy.sparse import csr_matrix
#from scipy.sparse.csgraph import floyd_warshall
#from scipy.sparse.csgraph import csgraph_from_dense
#from scipy.sparse.csgraph import dijkstra
#map(int,input().split())


# 枝刈り探索（分枝限定法）

class Knapsack:
	def __init__(self, VW):
		self.VW = VW
		self.VW.sort(key=lambda vw: vw[0] / vw[1], reverse=True)
		self.n = len(VW)
	
	def solve(self, capacity, ok=0):
		self.ok = ok
		self.capacity = capacity
		return self._dfs(0, 0, 0)
	
	def _dfs(self, i, v_now, w_now):
		if i == self.n:
			self.ok = max(self.ok, v_now)
			return v_now
		ng, f = self._solve_relaxation(i, self.capacity - w_now)
		ng += v_now
		if f:
			self.ok = max(self.ok, ng)
			return ng
		if ng < self.ok:
			return -float("inf")
		res = -float("inf")
		v, w = self.VW[i]
		if w_now + w <= self.capacity:
			res = max(res, self._dfs(i + 1, v_now + v, w_now + w))
		res = max(res, self._dfs(i + 1, v_now, w_now))
		return res
	
	def _solve_relaxation(self, i, capacity):
		res = 0
		f = True
		for v, w in self.VW[i:]:
			if capacity == 0:
				break
			if w <= capacity:
				capacity -= w
				res += v
			else:
				f = False
				res += v * (capacity / w)
				break
		return res, f

def main():
	n,t=map(int,input().split())
	AB = [list(map(int, input().split())) for _ in range(n)]
	AB.sort(key=lambda x:x[1],reverse=True)
	knapsack = Knapsack(AB)
	ans=knapsack.solve(t-1)+AB[-1][1]
	print(ans)
	
	
	

	
	
if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
import collections

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

dp = [collections.defaultdict(int) for _ in range(n + 1)]
dp[0][0] = 0
for i in sorted(range(n), key=lambda x: a[x]):
    for cur in dp[i]:
        dp[i + 1][cur] = max(dp[i + 1][cur], dp[i][cur])
        if cur < t:
            dp[i + 1][cur + a[i]] = max(dp[i + 1][cur + a[i]], dp[i][cur] + b[i])
print(max(dp[n].values()))

Submission status: Runtime Error

Solution code:
# ABC145e


def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**6)

    n, t = map(int, input().split())
    food = [tuple(map(int, input().split())) for _ in range(n)]

    # dp[i][j][k]=j番目まで見てiを頼まずにk分以下の注文の組み合わせで最大の美味しさ
    dp = [[[0] * (t) for i in range(10)] for j in range(n + 1)]

    for i in range(n+1):
        for j in range(n):
            for k in range(t):
                if i != j and k-food[j % 10][0] >= 0:
                    dp[i][j % 10][k] = max(dp[i][j % 10][k], dp[i][(j-1) % 10]
                                           [k - food[j][0]] + food[j][1])
                dp[i][j % 10][k] = max(
                    dp[i][j % 10][k], dp[i][(j - 1) % 10][k])
    ans = 0
    for i in range(n):
        ans = max(ans, max(dp[i][(n-1) % 10]) + food[i][1])
    # print(dp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
a,b=map(int,input().split())
c=[list(map(int,input().split())) for i in range(a)]
c.sort()
DP=[[0 for j in range(b+1)]for i in range(a)]
for i in range(c[0][0],b+1):
  DP[0][i]+=c[0][1]
for i in range(1,a):
  for j in range(c[i][0]):
    DP[i][j]=DP[i-1][j]
  for j in range(c[i][0],b):
    DP[i][j]=max(DP[i-1][j-c[i][0]]+c[i][1],DP[i-1][j])
  DP[i][b]=max(DP[i-1][b-1]+c[i][1],DP[i-1][b])
print(max(DP[-1]))

Submission status: Runtime Error

Solution code:
import sys


def solve():
    readline = sys.stdin.buffer.readline
    mod = 10 ** 9 + 7
    n, t = list(map(int, readline().split()))
    ls = [0] * (200 + 1)
    ab = []
    mt = 0
    for i in range(n):
        a, b = list(map(int, readline().split()))
        mt = max(mt, a)
        ab.append([a, b])
        for j in range(t, -1, -1):
            ls[j + a] = max(ls[j + a], ls[j] + b)
    print(max(ls[:t+mt]))


if __name__ == '__main__':
    solve()

Submission status: Runtime Error

Solution code:
#include<iostream>
#include<vector>
#include<string>
#include<cmath>
#include<limits>
#include<algorithm>
#include<numeric>
#include<utility>
#include<iomanip>

using ULLI = unsigned long long int;
using LLI = long long int;

using namespace std;

template<class T>
class ModCal{
private:
    const ULLI MAX = 1000000;
    ULLI mod;

    std::vector<T> fac;
    std::vector<T> finv;
    std::vector<T> inv;

    void COMinit() {
        fac.resize(MAX);
        finv.resize(MAX);
        inv.resize(MAX);

        fac[0] = fac[1] = 1;
        finv[0] = finv[1] = 1;
        inv[1] = 1;
        for (int i = 2; i < MAX; i++){
            fac[i] = fac[i - 1] * i % mod;
            inv[i] = mod - inv[mod%i] * (mod / i) % mod;
            finv[i] = finv[i - 1] * inv[i] % mod;
        }
    }
public:
    ModCal(ULLI _mod){
        this->mod = _mod;
        ModCal<T>::COMinit();
    }
    ModCal(){
        this->mod = 0;
    }

    T add(T a, T b){
        T tmp;
        tmp = a + b;
        if(mod != 0) tmp %= mod;
        return tmp;
    }

    T sub(T a, T b){
        T tmp;
        tmp = a - b;
        if(mod != 0){
            if(tmp < 0) tmp += mod;
            tmp %= mod;
        }
        return tmp;
    }

    T mul(T a, T b){
        T tmp;
        tmp = a * b;
        if(mod != 0) tmp %= mod;
        return tmp;
    }

    T modinv(T a, T m){
        T b = m, u = 1, v = 0;
        while (b) {
            T t = a / b;
            a -= t * b; std::swap(a, b);
            u -= t * v; std::swap(u, v);
        }
        u %= m;
        if (u < 0) u += m;
        return u;
    }

    T div(T a, T b){
        if(mod == 0){
            return a / b;
        }
        a %= mod;
        T tmp = a * ModCal<T>::modinv(b, mod) % mod;
        return tmp;
    }

    T pow(T a, T b){
        T tmp = 1;
        while(b > 0){
            if(mod != 0){
                if(b & 1) tmp = tmp * a % mod;
                a = a * a % mod;
            }else{
                if(b & 1) tmp *= a;
                a *= a;
            }
            b >>= 1;
        }
        return tmp;
    }

    // 以下の関数はMODを設定しない限り使えない
    // 無理やり使う場合は "ModCal<T> cal(Tの最大値)" でオブジェクトを作る
    T com(T n, T k){
        if(n < k) return 0;
        if(n < 0 || k < 0) return 0;
        return fac[n] * (finv[k] * finv[n - k] % mod) % mod;
    }

    T fact(T n){
        return fac[n];
    }
};

struct S{
    int A;
    int B;
    double v;

    S(int A, int B){
        this->A = A;
        this->B = B;
    }

    bool operator<(const S &l) const{
        return static_cast<double>(B)/A < static_cast<double>(l.B)/l.A;
    };
};

int main() {
    int N,T;
    vector<S> s;
    cin >> N >> T;

    for (int i = 0; i < N; i++) {
        double _A, _B;
        cin >> _A >> _B;
        S tmp = S(_A,_B);
        s.push_back(tmp);
    }

    sort(s.rbegin(),s.rend());

    int nowTime = 0;
    int res = 0;

    while(s.size()!=0){
        for(auto it=s.begin();it!=s.end();++it){
            if(nowTime < T){
                nowTime += it->A;
                res += it->B;
                s.erase(it);
                break;
            }
            if(it==s.end()-1){
                cout << res << endl;
                return 0;
            }
        }
    }

    cout << res << endl;
    return 0;
}

Submission status: Runtime Error

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

dp = [(0, set()) for _ in range(T)]
for i, pair in enumerate(zip(As, Bs)):
    ndp = []
    a, b = pair
    for t in range(T):
        tmpans = dp[t][0]
        tmpset = dp[t][1] | set()
        if t > a:
            tmpans2 = dp[t-a][0] + b
            if tmpans2 > tmpans:
                tmpans = tmpans2
                tmpset = dp[t-a][1] | {i}
        ndp.append((tmpans, tmpset))
    dp = ndp

ans, s = dp[-1]
ans += max([Bs[i] for i in range(N) if i not in s])
print(ans)

Submission status: Runtime Error

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

dp = [[0 for t_sum in range(T+3003)] for i in range(N)]

for i in range(N):
    for t_sum in range(T):

        # これは配るDP
        dp[i+1][t_sum+items[i][0]] = max(dp[i+1][t_sum+items[i][0]],
                                         dp[i][t_sum]+items[i][1])

        # i-1番目の品物を選ばない場合
        dp[i+1][t_sum] = max(dp[i+1][t_sum], dp[i][t_sum])


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

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
n, t = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n)]
ab.sort(key = lambda x:x[1])
dp = [[0 for j in range(t+1)] for i 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])
    for j in range(t):
        if j < t:
            next = min(j + ab[i][0], t)
            dp[i+1] [next] = max(dp[i+1][next], dp[i][j] + ab[i][1])
print(max(dp[n][t]))

Submission status: Runtime Error

Solution code:
import sys
from operator import itemgetter


def main():
    input = sys.stdin.readline
    N, T = map(int, input().strip().split())
    foods = sorted([(map(int, input().strip().split())) for _ in range(N)], key=itemgetter(0))

    ans = 0
    dp = [[0] * (T+1) for _ in range(N+1)]
    for j, food in enumerate(foods):
        n_a, n_b = food
        for k in range(T+1):
            if k == T:
                dp[j+1][k] = max(dp[j][k], dp[j][k-1]+n_b)
            elif k < n_a:
                dp[j+1][k] = dp[j][k]
            else:
                dp[j+1][k] = max(dp[j][k], dp[j][k-n_a]+n_b)
        #print(dp[j+1])
    ans = dp[-1][-1]
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import copy
 
def patterns(n):
    if(n==2):
        return [[0,1],[1,0]]
    else:
        a = patterns(n-1)
        new = []
        for i in a:
            for j in range(n):
                copied = copy.copy(i)
                copied.insert(j,n-1)
                new.append(copied)
        return new
 
N,T = (int(i) for i in input().split())
A = []
B = []
for i in range(N):
    Aj,Bj =  (int(j) for j in input().split())
    A.append(Aj)
    B.append(Bj)

maxsat = 0
for p in patterns(N):
    i = 0
    time = 0
    sat = 0
        
    while time < T-0.5 and i < N:
        time += A[p[i]]
        sat += B[p[i]]
        i += 1
    if sat > maxsat:
        maxsat = sat

print(maxsat)

Submission status: Runtime Error

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


def func(i,V,t):
    if(i>=N):
        return V
    if(t>=T):
        return V
    a=func(i+1,V+A[i][1],t+A[i][0])
    b=func(i+1,V,t)
    return max(a,b)
print(func(0,0,0))

Submission status: Runtime Error

Solution code:
n, t = [int(i) for i in input().split()]
ab = []
for _ in range(n):
    ab.append([int(i) for i in input().split()])
sb.sort(key=lambda x:x[0])
aa = t+max([i[0] for i in ab])+1
c = [0] * aa
for i in ab:
    d = c[:]
    for j in range(t):
        k = d[j]
        l = i[0] + j
        if l >= aa:
            continue
        c[l] = max(c[l], d[j] + i[1])
print(max(c))

Submission status: Runtime Error

Solution code:
import sys; readline = sys.stdin.readline
from collections import deque


N, T = map(int, readline().split())
A = [list(map(int, readline().split())) for i in range(N)]
A.sort(key=lambda x:-x[0])

w, v = zip(*A)
dp = [[-1 for i in range(T + 1)] for j in range(N + 1)]
def rec_dp(i, j, mini):
    if dp[i][j] != -1:
        return dp[i][j]
    
    if i == N:
        res = 0 if mini == i else v[mini]
    elif j < w[i]:
        res = rec_dp(i + 1, j, min(mini, i))
    else:
        res = max(rec_dp(i + 1, j, min(mini, i)), rec_dp(i + 1, j - w[i], i+1 if i==mini else mini) + v[i])
    
    dp[i][j] = res
    return res

ans = rec_dp(0, T, 0)

print(ans)

Submission status: Runtime Error

Solution code:
import numpy
dp = numpy.zeros((3001, 3001)) - 1

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

menus = [list(map(int, input().strip().split())) for i in range(N)]

def func(i, t, score):
  if dp[i][t] >= score:
    return;

  if t < 0:
    dp[i][T] = max(dp[i][T], score)
    return
  dp[i][t] = score
  if i == N: return
  func(i + 1, t, score)
  if t != 0:
    A, B = menus[i]
    func(i + 1, t - A, score + B)

func(0, T, 0)
print(int(dp.max()))

Submission status: Runtime Error

Solution code:
import numpy
dp = numpy.zeros((3000, 3000)) - 1

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

menus = [list(map(int, input().strip().split())) for i in range(N)]

def func(i, t, score):
  if dp[i][t] >= score:
    return;

  if t < 0:
    dp[i][T] = max(dp[i][T], score)
    return
  dp[i][t] = score
  if i == N: return
  func(i + 1, t, score)
  if t != 0:
    A, B = menus[i]
    func(i + 1, t - A, score + B)

func(0, T, 0)
print(int(dp.max()))

Submission status: Runtime Error

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

for i in range(n):
    a,b = map(int,input().split())
    ls.append([a,b,a/b])

ls = sorted(ls, key=lambda x:x[2])    
    
for i in range(1,len(ls)):
    ls[i][0] = ls[i-1][0]+ls[i][0]
    ls[i][1] = ls[i-1][1]+ls[i][1]

print(ls)
ans = []    
for i in range(n):
  for j in range(1,n):
      if ls[i][0] + ls[j][0] <= t:
        ans.append(ls[i][1] + ls[j][1])
  if ls[i][0] <= t:
        ans.append(ls[i][1])
    
print(max(ans))

Submission status: Runtime Error

Solution code:
#E-all you can eat
n,t=map(int,input().split())
how=0
T=how+t-1
uselist=[list(map(int,input().split())) for i in range(n)]
lists=sorted(uselist,key=lambda x: (-x[1],x[0]))
print(lists)
j=0
def search():
    global T
    global ans
    ans=0
    T=T
    flag2=True
    flag=False
    for i in range(n):
        print(lists[i])
        if lists[i][0]<=T:
            ans+=lists[i][1]
            T-=lists[i][0]
            lists[i]=[10**9,10**9]
            flag=True
            break
        else:
            continue
    if not flag:
        flag2=False
        j=ans

    if T>=0 and flag2:
        return search()
search()
print(j)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(3001)
N, T = map(int, input().split())
As = []
Bs = []
for i in range(N):
    a, b = map(int, input().split())
    As.append(a)
    Bs.append(b)

memo = {}
def dp(i, t):
    if i >= N:
        return 0, set()
    if (i, t) in memo:
        return memo[(i, t)]
    a, b = As[i], Bs[i]
    ret, s = dp(i+1, t)
    if t > a:
        ret2, s2 = dp(i+1, t-a)
        ret2 += b
        if ret2 > ret:
            ret = ret2
            s.add(i)
    memo[(i, t)] = ret, s
    return ret, s

ret, s = dp(0, T)
print(ret, s)
print(Bs)
print(sum(Bs))
maxB = 0
for i in range(N):
    if i not in s:
        maxB = maxB if maxB > Bs[i] else Bs[i]
print(ret + maxB)

Submission status: Runtime Error

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

sys.setrecursionlimit(10**7)
inf=10**20
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 [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

n,t=LI()
t-=1
dp=[[-1]*3010 for _ in range(3010)]
l=[LI() for _ in range(n)]
l=sorted(l,key=lambda x:x[1])

def rec(i,j,cnt):
  if dp[i][j]>=0:
    return dp[i][j]

  res=0
  if i==n:
    res=0
  elif j<=0:
    cnt+=1
    res=max(rec(i+1,j,cnt),rec(i+1,j-l[i][0],cnt)+l[i][1])
  else:
    cnt+=1
    res=max(rec(i+1,j,cnt),rec(i+1,j-l[i][0],cnt)+l[i][1])
  dp[i][j]=res
  return res

def main():
  return rec(0,t,0)

# main()
print(main())

Submission status: Runtime Error

Solution code:
n,t = = map(int,input().split())
a = [0]*n
b = [0]*n
for i in range(n):
    a[i],b[i] = map(int,input().split())
c = zip(a,b)
c.sorted()
a,b = zip(*c)
dp[][] = [[0]*n]*t
for i in range(1,n):
    for i in range(t):
        dp[i][j] = max(dp[i-a[j]][j-1]+b[j],dp[i][j-1])
print(dp[n-1][t-1])

Submission status: Runtime Error

Solution code:
# E
import numpy as np
N, T = map(int, input().split())
# A=cost. B=value
A, B = np.array([input().split() for _ in range(N)], dtype=int).T

weight,value = A, B
# dp[i][w] = i番目までからwを超えないように選んだ時の最大値, まだ最後の食べ物を選んでない
d0 = np.zeros((N,T),int)
# dp[i][w] = i番目までからwを超えないように選んだ時の最大値, もう最後の食べ物を選んだ
d1 = np.zeros((N,T),int)
# 初期値として0番目の商品を加える
d0[0,weight[0]:] = value[0]
d1[0,:] = value[0]

for n in range(1, N):
  for w in range(T):
    if (w >= weight[n]):
      d0[n][w] = np.max(d0[n-1][w-weight[n]] + value[n], d0[n-1][w])
      d1[n][w] = np.max(d1[n-1][w-weight[n]] + value[n], d1[n-1][w], d0[n-1][w] + value[n])
    else:
      d0[n][w] = d0[n-1][w]
      d1[n][w] = np.max(d1[n-1][w], d0[n-1][w] + value[n])

print(d1[-1,-1])

Submission status: Runtime Error

Solution code:
def knapsack(N,W,weight,value):
  #初期化
  inf=float("inf")
  dp=[[-inf for i in range(W+1)] for j in range(N+1)]
  for i in range(W+1): dp[0][i]=0

  #DP
  for i in range(N):
    for w in range(W+1):
      if weight[i]<=w: #dp[i][w-weight[i]の状態にi番目の荷物が入る可能性がある
        dp[i+1][w]=max(dp[i][w-weight[i]]+value[i], dp[i][w])
      else: #入る可能性はない
        dp[i+1][w]=dp[i][w]
  return dp[N][W]

for i in range(N):
  t,v = map(int,input().split())
  time.append(t)
  value.append(v)

print(knapsack(N,T,time,value))

Submission status: Runtime Error

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]

d=sorted(d,key=lambda x:x[a])
dp=[-1]*(3000*2+5)
dp[0]=0
for i in range(len(d)):
  for j in range(T-1,-1,-1):
    if dp[j]!=-1:
      if dp[j]+d[i][1]>dp[j+d[i][0]]:
        dp[j+d[i][0]]=dp[j]+d[i][1]
      
print(max(dp))

Submission status: Runtime Error

Solution code:
import copy
n,t = map(int,input().split())
ab = [[int(i) for i in input().split()] for j in range(n)]

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

for i in range(n):
    for j in range(t):
        dp[i+1][j] = dp[i][j]
        li[i+1][j] = li[i][j]
        #print(j,ab[i][0])
        if j < ab[i][0]:
            continue
        if dp[i][j] < dp[i][j-ab[i][0]] + ab[i][1]:
            dp[i+1][j] = dp[i][j-ab[i][0]] + ab[i][1]
            li[i+1][j].append(i)
        #dp[i+1][j] = max(dp[i][j],dp[i][j-ab[i][0]] + ab[i][1])

abcopy = copy.deepcopy(ab)
abcopy.sort()

plus = 0
for i in range(n):
    if i in li:
        continue
    else:
        plus = abcopy[i][0]

print(dp[n][t]+plus)

Submission status: Runtime Error

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

sys.setrecursionlimit(10**7)
inf=10**20
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 [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

n,t=LI()
t-=
dp=[[-1]*3010 for _ in range(3010)]
l=[LI() for _ in range(n)]
l=sorted(l,key=lambda x:x[1])

def rec(i,j,cnt):
  if dp[i][j]>=0:
    return dp[i][j]

  res=0
  if i==n:
    res=0
  elif j<=0:
    cnt+=1
    res=max(rec(i+1,j,cnt),rec(i+1,j-l[i][0],cnt)+l[i][1])
  else:
    cnt+=1
    res=max(rec(i+1,j,cnt),rec(i+1,j-l[i][0],cnt)+l[i][1])
  dp[i][j]=res
  return res

def main():
  return rec(0,t,0)

# main()
print(main())

Submission status: Runtime Error

Solution code:
import copy
 
def patterns(n):
    if(n==2):
        return [[0,1],[1,0]]
    else:
        a = patterns(n-1)
        new = []
        for i in a:
            for j in range(n):
                copied = copy.copy(i)
                copied.insert(j,n-1)
                new.append(copied)
        return new
 
N,T = (int(i) for i in input().split())
A = []
B = []
for i in range(N):
    Aj,Bj =  (int(j) for j in input().split())
    A.append(Aj)
    B.append(Bj)

maxsat = 0
ex = []
for p in patterns(N):
    i = 0
    time = 0
    sat = 0
    for a in ex:
        if(p[0:len(a)] == a):
            continue
        
    while time < T-0.5 and i < N:
        time += A[p[i]]
        sat += B[p[i]]
        i += 1
    if not i == N:
        ex.append(p[0:i])
    if sat > maxsat:
        maxsat = sat

print(maxsat)

Submission status: Runtime Error

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

class Item:

    def __init__(self, value, weight):
        self.value = value
        self.weight = weight
        self.density = value / weight

    def __str__(self):
        return f'weight = {self.weight}, value = {self.value}'


class Knapsack:

    def __init__(self, weight_limit):
        self.weight_limit = weight_limit
        self.weight = 0
        self.value = 0
        self.items = []

    def add(self, item):
        if self.weight + item.weight <= self.weight_limit:
            self.weight += item.weight
            self.value += item.value
            self.items.append(item)

    def show(self):
        return self.value


def buildItems():
    lst = []
    weights = []
    values = []
    for i in range(n):
        lsti = list(map(int, input().split()))
        lst.append(lsti)
    lst.sort(key= lambda x: x[1])
    saidai = lst.pop()[1]
    for i in range(n-1):
        weights.append(lst[i][0])
        values.append(lst[i][0])
    return [Item(*params) for params in zip(values, weights)], saidai


def testGreedys(weight_limit=t-1):
    def packing(greedy):
        knapsack = Knapsack(weight_limit)
        for item in sorted(items, key=greedy, reverse=True):
            knapsack.add(item)
        return knapsack.show()

    items, saidai = buildItems()
    ans1 = packing(lambda item: item.value)    # 高価値優先
    ans2 = packing(lambda item: -item.weight)  # 軽量優先
    ans3 = packing(lambda item: item.density)  # 高密度優先
    print(max(ans1, ans2, ans3)+saidai)

if __name__ == '__main__':
    testGreedys()

Submission status: Runtime Error

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

def answer():
    N, T = map(int, input().split())
    dishes = [list(map(int, input().split())) for _ in range(N)]
    
    for i in range(len(dishes)):
        dishes[i][2] = dishes[i][1] / dishes[i][0]
    dishes = sorted(dishes, key=lambda x: x[2])

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

    def search(i, u):
        if dp[i][u]:
            return dp[i][u]
        if i == N:
            result = 0
        elif u > T - 0.5:
            result = search(i+1, u)
        else:
            w = dishes[i][0]
            v = dishes[i][1]

            res1 = search(i+1, u)
            res2 = search(i+1, u-w) + v
            result = max(res1, res2)

        dp[i][u] = result
        return result

    print(search(0, T-1))


if __name__ == '__main__':
    answer()

Submission status: Runtime Error

Solution code:
N,T = map(int,input().split())
DP = [[0 for _ in range(6001)] for _ in range(2)]
bit = 0
for i in range(N):
    A,B = map(int,input().split())
    for j in range(T):
        DP[bit][j+A] = max(DP[bit^1][j+A],DP[bit^1][j]+B,DP[bit][j+A-1])
    for j in range(T):
        DP[bit^1][j] = 0
    bit ^= 1
    print(np.array(DP[bit^1]))
print(max(DP[bit^1]))

Submission status: Runtime Error

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


def func(i,V,t):
    if(i>=N):
        return V
    if(t+A[i][0]>T):
        return V
    a=func(i+1,V+A[i][1],t+A[i][0])
    b=func(i+1,V,t)
    return max(a,b)
print(func(0,0,0))

Submission status: Runtime Error

Solution code:
def knapsack(N,W,weight,value):
    dp = np.zeros(((N+1),(W+1)))
    F=[[[] for i in range(W+1)] for j in range(N+1)]
    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]
                    F[i+1][w] =F[i][w]
                else:
                    dp[i+1][w] = dp[i][w-weight[i]]+value[i]
                    F[i+1][w] = F[i][w-weight[i]] + [i]
            else:
                dp[i+1][w]=dp[i][w]
                F[i+1][w] =F[i][w]
    return dp[N][W],F[N][W]

if __name__ == "__main__":
    N,T = map(int,input().split())
    D = []
    E = []
    for i in range(N):
        A,B = map(int,input().split())
        D.append(A)
        E.append(B)
    ans,F = knapsack(N,T-1,D,E)
    max = 0
    for i in range(N):
        if i in F:
            continue
        if max <= E[i]:
            max = E[i]
    print(int(ans+max))

Submission status: Runtime Error

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]

dp=[-1]*(30*2)
dp[0]=0
for i in range(len(d)):
  for j in range(T,-1,-1):
    if dp[j]!=-1:
      if dp[j]+d[i][1]>dp[j+d[i][0]]:
        dp[j+d[i][0]]=dp[j]+d[i][1]
      
print(max(dp))

Submission status: Runtime Error

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


items = sorted([tuple(map(int, input().split()))
                for i in range(N)], key=lambda x: x[0])

if sum([v[0] for v in items[:-1]]) < T:
    print(sum([v[1] for v in items]))
    exit()
items = sorted([tuple(map(int, input().split()))
                for i in range(N)], key=lambda x: (x[1], x[0]))

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

for i in range(N-1):
    for t_sum in range(T):

        # これは配るDP
        if t_sum+items[i][0] < T:
            dp[i+1][t_sum+items[i][0]] = max(dp[i+1][t_sum+items[i][0]],
                                             dp[i][t_sum]+items[i][1])

        # i-1番目の品物を選ばない場合
        dp[i+1][t_sum] = max(dp[i+1][t_sum], dp[i][t_sum])

# print(dp[N-1])

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

Submission status: Runtime Error

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

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

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

    def search(i, u):
        if dp[i][u]:
            return dp[i][u]
        if i == N:
            result = 0
        elif u > T - 0.5:
            result = search(i+1, u)
        else:
            w = dishes[i][0]
            v = dishes[i][1]

            res1 = search(i+1, u)
            res2 = search(i+1, u-w) + v
            result = max(res1, res2)

        dp[i][u] = result
        return result

    print(search(0, T-1))


if __name__ == '__main__':
    answer()