Problem:


Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^9

1 \leq w_i \leq W

1 \leq v_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

1 1000000000
1000000000 10

Sample Output 2

10

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.



Sample input:
3 8
3 30
4 50
5 60


Sample output:
90

Submission status: Accepted

Solution code:
n,w = map(int, input().split())
wv = []
vsum=0
for _ in range(n):
    tmp = list(map(int,input().split()))
    wv.append(tmp)
    vsum += tmp[1]

dp = [[float("inf") for i in range(vsum+1)] for j in range(n+1)]
dp[0][0]=0

for i in range(1,n+1):
    now_w,now_v =wv[i-1]
    for v in range(vsum+1):
        dp[i][v] = dp[i-1][v]
        if v - now_v >= 0:
            dp[i][v] = min(dp[i][v],dp[i-1][v-now_v] + now_w)

ans=0
for val in range(len(dp[-1])):
    if dp[-1][val] <= w:
        ans=val
print(ans)

Submission status: Accepted

Solution code:
N, W = map(int, input().split())
w, v = [], []
for i in range(N):
	x, y = map(int, input().split())
	w.append(x)
	v.append(y)

VMAX = 1000
INF = 1 << 30
dp = [[INF] * (N * VMAX + 1) for _ in range(N + 1)]
dp[0][0] = 0

for i in range(N):
	for j in range(N * VMAX + 1):
		if j < v[i]:
			dp[i + 1][j] = dp[i][j]
		else:
			dp[i + 1][j] = min(dp[i][j], dp[i][j - v[i]] + w[i])

res = 0
for i in range(N * VMAX + 1):
	if dp[N][i] <= W:
		res = i
print(res)

Submission status: Accepted

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


def solve(N: int, W: int, w: "List[int]", v: "List[int]"):
    total_value = sum(v)
    dp = [[float("inf")] * (total_value + 1) for _ in range(N+1)]
    for i in range(N+1):
        dp[i][0] = 0

    for i in range(N):
        for j in range(1, total_value+1):
            if j - v[i] >= 0:
                dp[i+1][j] = min(
                    dp[i][j],
                    dp[i][j-v[i]] + w[i]
                )
            else:
                dp[i+1][j] = dp[i][j]

    weight = 0
    res = 0
    for j in range(total_value+1):
        if dp[-1][j] <= W:
            weight = dp[-1][j]
            res = j
    print(res)


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    w = [int()] * (N)  # type: "List[int]"
    v = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        w[i] = int(next(tokens))
        v[i] = int(next(tokens))
    solve(N, W, w, v)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, w = map(int, input().split())
ws, vs = [], []
for _ in range(n):
    wi, vi = map(int, input().split())
    ws.append(wi)
    vs.append(vi)
sum_v = sum(vs)
dp = [float('inf')] * (sum_v + 1)
dp[0] = 0
for i in range(n):
    for j in range(sum_v - vs[i], -1, -1):
        dp[j + vs[i]] = min(dp[j] + ws[i], dp[j + vs[i]])
ans = 0
for vi, wi in enumerate(dp):
    if wi <= w:
        ans = vi
print(ans)

Submission status: Accepted

Solution code:
N, W = map(int, input().split())
w, v = [0] * N, [0] * N
for i in range(N):
	w[i], v[i] = map(int, input().split())

V = sum(v)
# dp[i][j]:i番目までの品物から価値がj以上になるよう選んだときの重さの総和の最小値
dp = [[float("inf")] * (V + 1) for _ in range(N + 1)]
dp[0][0] = 0
for i in range(N):
	for j in range(V + 1):
		# i+1番目を選ぶ場合
		if j - v[i] >= 0:
			dp[i + 1][j] = min(dp[i + 1][j], dp[i][j - v[i]] + w[i])
		# i+1番目を選ばない場合
		dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])

# dp[N][j]がW以下であるようなjの最大値が答えになる
ans = 0
for j in range(V + 1):
	if dp[N][j] <= W:
		ans = j

print(ans)

Submission status: Accepted

Solution code:
import numpy as np

N, W = map(int, input().split())
pairs = list(tuple(map(int, input().split())) for _ in range(N))
v_sum = sum(v for _, v in pairs)

dp = np.full((N+1, v_sum+1), W * 2, dtype = np.int64)
dp[0][0] = 0

for (i, (w, v)) in enumerate(pairs):
    dp[i+1] = dp[i]
    dp[i+1, v:] = np.minimum(dp[i+1, v:], dp[i, :v_sum-v+1] + w)

print(max(np.where(dp[N] <= W)[0]))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
import numpy as np
 
N,W = map(int, input().split())
 
dp = [10 ** 10] * (N * (10 ** 3) + 1)
dp[0] = 0
dp = np.array(dp)
 
 
for i in range(N):
    w,v = map(int, input().split())
    dp[v:] = np.minimum(dp[v:] , dp[:-v] + w)
  
for i,count in enumerate(dp):
    if dp[i] <= W:
        ans = i
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
import numpy as np
 
N,W = map(int, input().split())
 
dp = [10 ** 10] * N * (10 ** 4)
dp[0] = 0
dp = np.array(dp)
 
 
for i in range(N):
    w,v = map(int, input().split())
    dp[v:] = np.minimum(dp[v:] , dp[:-v] + w)
  
for i,count in enumerate(dp):
    if dp[i] <= W:
        ans = i
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
 
N, W = map(int, input().split())
WV = np.array([input().split() for _ in range(N)], np.int64)
V = sum(WV[:,1])
dp = np.zeros(V + 1, np.int64)
dp += 10 ** 10
dp[0] = 0
for w, v in WV:
    dp[v:] = np.minimum(dp[v:], dp[:-v] + w)
for v in range(V + 1):
    if dp[v] <= W:
        ans = v
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
from functools import lru_cache
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp():
    '''
    一つの整数
    '''
    return int(input())
def inpl():
    '''
    一行に複数の整数
    '''
    return list(map(int, input().split()))
def inpl_str():
    '''
    一行に複数の文字
    '''
    return list(input().split())

n, k = inpl()
max_value = 10 ** 5 + 1
# max_value=140+1
dp = [[INF] * max_value for i in range(n + 1)]
dp[0][0]=0
for i in range(n):
    w, v = inpl()
    for j in range(max_value):
        include = dp[i][j-v] + w if j-v>=0 else INF
        not_include = dp[i][j]
        dp[i + 1][j] = min(include, not_include)
tmp = dp[n][:]
for i in range(max_value-1, -1, -1):
    if tmp[i] <=k:
        print(i)
        break
# for i in dp:
#     print(i)

Submission status: Accepted

Solution code:
import numpy as np

N, W = map(int, input().split())
WV = np.array([input().split() for _ in range(N)], np.int64)
V = sum(WV[:,1])
dp = np.zeros(V + 1, np.int64)
dp += 10 ** 10
dp[0] = 0
for w, v in WV:
    dp[v:] = np.minimum(dp[v:], dp[:-v] + w)
for v in range(V + 1):
    if dp[v] <= W:
        ans = v
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
N,W = map(int,input().split())
dp = np.full(N*1000+1,W+1)
dp[0] = 0
for _ in range(N):
    w,v = map(int,input().split())
    dp[v:]=np.minimum(dp[v:],dp[:-v]+w)
print(np.where(dp<=W)[0][-1])

Submission status: Accepted

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

dp = [10**10]*(10**5)
dp = np.array(dp)

for _ in range(n):
    w, v = map(int, input().split())
    np.minimum(dp[v:], dp[:-v] + w, out=dp[v:])
    np.minimum(w, dp[:v], out=dp[:v])
    
#print(dp[:101])
#print(dp[91])
value = 10**5
for i in dp[::-1]:
    if i <= W:
        print(value)
        exit()
    value -= 1

Submission status: Accepted

Solution code:
import numpy as np

N, W = map(int, input().split())
WV = np.array([input().split() for _ in range(N)], np.int64)
V = sum(WV[:, 1])
INF = 1 << 60
dp = np.full(V + 1, INF)
dp[0] = 0
for w, v in WV:
    np.minimum(dp[v:], dp[:-v] + w, out=dp[v:])
for v in range(V + 1):
    if dp[v] <= W:
        ans = v
print(ans)

Submission status: Accepted

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

v = [0] * N
w = [0] * N
for i in range(N):
    w[i],v[i] = map(int,input().split())
sumv = sum(v)+1
dp = [[float('inf')] * (sumv) for _ in range(N+1)]
for i in range(N):
    dp[i][0] = 0
for i in range(1, N+1):
    for j in range(1, sumv):
        if v[i-1] > j:
            dp[i][j] = dp[i-1][j]
        else:
            dp[i][j] = min(dp[i-1][j],w[i-1]+dp[i-1][j-v[i-1]])
ans = 0
for i in range(1, sumv+1):
    if dp[N][-i] <= W:
        ans = sumv - i
        break
print(ans)

Submission status: Accepted

Solution code:
n,wmax=map(int,input().split())
v=[0]*n
w=[0]*n
for i in range(n):
    w[i],v[i]=list(map(int,input().split()))
sv=sum(v)+1
dp=[[float('inf')]*sv for _ in range(n)]
dp[0][v[0]-1]=w[0]
for i in range(n):
    dp[i][0]=0
for i in range(n):
    for j in range(sv):
        dp[i][j]=min(dp[i-1][j],dp[i-1][j-v[i]]+w[i])
ans=float('inf')
for p in range(sv-1,-1,-1):
    if dp[n-1][p]<=wmax:
        ans=p
        break
print(ans)

Submission status: Accepted

Solution code:
n,wmax=map(int,input().split())
v=[0]*n
w=[0]*n
for i in range(n):
    w[i],v[i]=list(map(int,input().split()))
sv=sum(v)+1
dp=[[float('inf')]*sv for _ in range(n)]
dp[0][v[0]-1]=w[0]
for i in range(n):
    dp[i][0]=0
for i in range(n):
    for j in range(sv):
        dp[i][j]=min(dp[i-1][j],dp[i-1][j-v[i]]+w[i])
ans=float('inf')
for p in range(sv-1,-1,-1):
    if dp[n-1][p]!=ans and dp[n-1][p]<=wmax:
        ans=p
        break
print(ans)

Submission status: Accepted

Solution code:
N, W = map(int, input().split())
wv = []
for _ in range(N):
    wv.append(tuple(map(int, input().split())))

INF = 10**10
dp = [INF]*(10**5+1)
dp[0] = 0
for w, v in wv:
    newdp = dp[:]
    for vv in range(10**5):
        if v+vv>10**5:
            break
        newdp[v+vv] = min(dp[v+vv], dp[vv]+w)
    dp = newdp
for v, w in enumerate(reversed(dp)):
    if w<=W:
        print(10**5-v)
        break

Submission status: Accepted

Solution code:
n, w = map(int, input().split())
x = []
y = []

for i in range(n):
  a,b = map(int, input().split())
  x.append(b)
  y.append(a)

max_num = sum(x)

dp = [[float("inf")] * (max_num + 1) for i in range(n + 1)]
dp[0][0] = 0

for i in range(n):
  for j in range(max_num + 1):
    if(j >= x[i]):
      dp[i + 1][j] = min(dp[i + 1][j], dp[i][j - x[i]] + y[i])
    dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])
    
print(max(list(int(i) for i in range(max_num + 1) if dp[n][i] <= w)))

Submission status: Accepted

Solution code:
n, max_weight = map(int, input().split())
WV = [list(map(int, input().split())) for _ in range(n)]
W, V = zip(*WV)
M = sum(V) + 1
#M = 100100
INF = 1 << 60
dp = list([INF] * M for _ in range(n + 1))
dp[0][0] = 0
for i in range(n):
    for v in range(M):
        if v >= V[i]:
            dp[i + 1][v] = min(dp[i][v], dp[i][v - V[i]] + W[i])
        else:
            dp[i + 1][v] = dp[i][v]
for v in range(M):
    if dp[n][v] <= max_weight:
        ans = v
print(ans)

Submission status: Accepted

Solution code:
N,W= map(int,input().split())
w=[]
v=[]
for  i in range(N):
    a,b=map(int,input().split())
    w.append(a)
    v.append(b)

V=sum(v)

dp =[ [float('inf')]*(V+1) for _ in range(N+1) ]
for  i in range(N):
    dp[i][0]=0
for i in range(N):
    for  j in range(V+1):
        dp[i+1][j]=dp[i][j]
        if j-v[i]>=0:
            dp[i+1][j]= min(dp[i][j] , dp[i][j-v[i]]+w[i])

ans=0
for i in range(N+1):
    for  j in range(V+1):
        if 0<dp[i][j]<=W:
            ans=max(ans,j)

print(ans)

Submission status: Accepted

Solution code:
INF = 10**13

N, W = map(int, input().split())
w = [0]*N
v = [0]*N
for i in range(N):
    w[i], v[i] = map(int, input().split())

dp = [[INF]*100010 for _ in range(N+1)]

for i in range(N):
    for now_v in range(100010):
        if now_v - v[i] >= 0:
            dp[i+1][now_v] = min(dp[i][now_v], dp[i][now_v-v[i]]+w[i])
        else:
            dp[i+1][now_v] = min(dp[i][now_v], w[i])

for ans_v in range(100010):
    if dp[N][ans_v] > W:
        ans = ans_v
        break
print(ans)

Submission status: Accepted

Solution code:
N,W=map(int,input().split())
k=[[0,0] for i in range(N)]
dp=[[W+1]*(1001*101+1) for j in range(N+1)]
R=set()
for i in range(N):
    k[i][0],k[i][1]=map(int,input().split())
#dp[0][:k[0][1]]=[k[0][0]]*(k[0][1]+1)
dp[0][0]=0
for i in range(0,N):
    for v in range(1001*101):
        if v - k[i][1]>=0:
            dp[i+1][v] = min(dp[i][v-k[i][1]]+k[i][0],dp[i][v])
        else:
            dp[i+1][v]=min(dp[i+1][v],dp[i][v])

        if dp[i][v]<W:
             R.add(v)


for v in reversed(range(1001*101+1)):
    if dp[N][v]<=W:
        print(v)
        exit()

Submission status: Accepted

Solution code:
N,W=map(int,input().split())
k=[[0,0] for i in range(N)]
dp=[[W+1]*(1001*101+1) for j in range(N+1)]
R=set()
for i in range(N):
    k[i][0],k[i][1]=map(int,input().split())
dp[0][:k[0][1]]=[k[0][0]]*(k[0][1]+1)
dp[0][0]=0
for i in range(1,N):
    for v in range(1001*101):
        if v - k[i][1]>=0:
         dp[i][v] = min(dp[i-1][v-k[i][1]]+k[i][0],dp[i-1][v])
        else:
            dp[i][v]=min(dp[i-1][v],dp[i][v])

        if dp[i][v]<W:
             R.add(v)


for v in reversed(range(1001*101+1)):
    if dp[N-1][v]<=W:
        print(v)
        exit()

Submission status: Accepted

Solution code:
#DP-E
def main():
    import sys, copy
    N, W = map(int, sys.stdin.readline().split())
    L = tuple([tuple(map(int, sys.stdin.readline().split())) for _ in range(N)])
    #print(L)
    #価値テーブルを作成
    dp =[[10**11+1 for _ in range(10**5+1)] for _ in range(N)]
    dp[0][L[0][1]] = L[0][0] #初期設定
    #print(dp)
    for i in range(1, N):
        #1. 前回のコピー
        dp[i] = copy.copy(dp[i-1]) 
        w, v = L[i][0], L[i][1]
        #print(w, v)
        #2. 今回の荷物の更新
        dp[i][v] = min(w, dp[i][v])
        #3. 前回の荷物 + 今回の荷物の更新
        for j in range(10**5+1-v):
            if dp[i-1][j] !=0:
                dp[i][v+j] = min(dp[i][v+j], w + dp[i-1][j])
    
    
    
    ans = 0
    for v1,w1 in enumerate(dp[-1]):
        if w1 <= W:
            if ans < v1:
                ans = v1
            #print(v1, w1)
    print(ans)

if __name__ =='__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np

sys.setrecursionlimit(10 ** 8)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, W = map(int, readline().split())
things = []
vsum = 0
for i in range(N):
    weight, value = map(int, readline().split())
    things.append((weight, value))
    vsum += value


INF = 1 << 62


def solve():
    dp = INF * np.ones(vsum + 1, dtype=int)
    w0, v0 = things[0]
    dp[0] = 0
    dp[v0] = w0
    for i in range(1, N):
        w, v = things[i]
        np.minimum(dp[v:], dp[:-v] + w, out=dp[v:])
    return np.where(dp <= W)[0][-1]


if __name__ == "__main__":
    print(solve())

Submission status: Accepted

Solution code:
#-------------------------------------------------------------------
import sys
def p(*_a):
  _s=" ".join(map(str,_a))
  #print(_s)
  sys.stderr.write(_s+"\n")
#-------------------------------------------------------------------

N, W = map(int, input().split())
WV = [[0,0]]+[ list(map(int, input().split())) for _ in range(N) ]

#p(WV)

initW = 10**9+1

vmax = 1000*100

#値：w重さ (横：v価値)(縦：n品物)
dp = [[initW for v in range(vmax+1)] for _r in range(N+1)]

dp[0][0] = 0	#初期条件(必須！)


for iN in range(1,N+1):
	for iV in range(vmax+1):
		w,v = WV[iN]
		
		w0 =      dp[iN-1][iV]
		w1 = (w + dp[iN-1][iV-v]) if (iV-v >= 0) else initW
	
		dp[iN][iV] = min(w0, w1)

ans=0

for iV in range(vmax+1):
	w = dp[N][iV]
	if w>W: continue
	ans = max(ans,iV)

print(ans)

Submission status: Accepted

Solution code:
n, W = map(int, input().split())
w, v = [0]*n, [0]*n
for i in range(n):
    w[i], v[i] = map(int, input().split())

# Dのように品物と重さでループまわすとO(nW)で今W<=10**9だから間に合わない
# 品物と価値でループ回す
# dp[i][j]の意味はi番目までの品物で、価値j以上となるように選んだ時の、重さの最小値
sum_v = sum(v)
dp = [[float("inf")]*(sum_v+1) for i in range(n+1)]
dp[0][0] = 0
for i in range(n):
    for j in range(sum_v+1):
        if j - v[i] >= 0:
            dp[i+1][j] = min(dp[i+1][j], dp[i][j-v[i]] + w[i])
        dp[i+1][j] = min(dp[i+1][j], dp[i][j])
#print(dp)
ans = 0
for j in range(sum_v+1):
    if dp[n][j] <= W:
        ans = j
print(ans)

Submission status: Accepted

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

N, W = list(map(int, input().split()))
W_l = []
V_l = []
for i in range(N):
    w, v = list(map(int, input().split()))
    W_l.append(w)
    V_l.append(v)

V_max = sum(V_l)+1
W_max = sum(W_l) +1

#print(V_max, W_max)
dp = [[W+1] * V_max for _ in range(N+1)]
dp[0][0] = 0
for i in range(N):
    #print(i)
    for v in range(V_max):
        if v -V_l[i] >= 0:
            dp[i+1][v] = min(dp[i][v-V_l[i]]+W_l[i], dp[i][v])
        else:
            dp[i+1][v] = dp[i][v]
    #print(dp)
ans = 0
#print(dp[-1])
for v, w in enumerate(dp[-1]):
    if w <= W and ans <= v:
        ans = v
print(ans)

Submission status: Accepted

Solution code:
N,W = list(map(int,input().split()))
WV = []
Vsum = 0
for i in range(N):
    [Wtmp,Vtmp] = list(map(int,input().split()))
    WV.append([Wtmp,Vtmp])
    Vsum += Vtmp

inf = float('inf')
dp = [[inf]*(Vsum+1) for i in range(N)]

W0 = WV[0][0]
V0 = WV[0][1]

for j in range(Vsum+1):
    if V0>=j:
        dp[0][j] = W0

for i in range(1,N):
    newW = WV[i][0]
    dp[i][0] = min(newW,dp[i-1][0])

for i in range(1,N):
    newW = WV[i][0]
    newV = WV[i][1]
    for j in range(1,Vsum+1):
        if j<=newV:
            dp[i][j] = newW
        if j-newV>=0:
            dp[i][j] = min(dp[i-1][j-newV]+newW,dp[i][j])
        dp[i][j] = min(dp[i-1][j],dp[i][j])

out = 0
for i in range(N):
    for j in range(Vsum+1):
        if dp[i][j]<=W:
            if j >= out:
                out = j

print(out)
#print(*dp,sep='\n')

Submission status: Accepted

Solution code:

class obj:
    def __init__(self,w,v):
        self.w = w
        self.v = v
        self.r = v/w

x = input().split()
N = int(x[0])
M = int(x[1])
item = []
item = []
for i in range(N):
    x = input().split()
    item.append(obj(int(x[0]),int(x[1])))

maxV = 0


def getKey(x):
    return x.r


item.sort(key=getKey, reverse=True)
	
def Bound(i, C):	# object i -> n-1, capacity = C
    global item, N
    
    sw = 0
    sv = 0
    j = i
    f = 1.0
    while j < N and f == 1.0:
        wj = min(C-sw, item[j].w)
        f = float(wj)/item[j].w
        sw += f*item[j].w
        sv += f*item[j].v
        j += 1
    return sv



def dfsv4(i, sumW, sumV):
    """prning bounding, branching"""
    global maxV, item, N, M
    if i == N:
        if sumW <= M:
            maxV = max(maxV, sumV)
    else:   
        temp1 = Bound(i+1, M-sumW) + sumV
        temp2 = Bound(i,M-sumW) + sumV
        is1 = False

        if temp1 > temp2:
            is1 = True

        if is1:
            if temp1 > maxV:
                dfsv4(i+1, sumW, sumV)
            if sumW + item[i].w <= M:
                if temp2 > maxV:
                    dfsv4(i+1, sumW+item[i].w, sumV+item[i].v)
        else:
            if sumW + item[i].w <= M:
                if temp2 > maxV:
                    dfsv4(i+1, sumW+item[i].w, sumV+item[i].v)
            if temp1 > maxV:
                dfsv4(i+1, sumW, sumV)


dfsv4(0,0,0)

print(maxV)

Submission status: Accepted

Solution code:
# region fastio  # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os

BUFSIZE = 8192


class FastIO(io.IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = io.BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(io.IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

def main():

    from bisect import bisect_left as bl, bisect_right as br, insort
    import sys
    import heapq
    # from math import *
    from collections import defaultdict as dd, deque
    def data():
        return sys.stdin.readline().strip()

    def mdata():
        return map(int, data().split())

    out = sys.stdout.write
    # sys.setrecursionlimit(100000)
    INF = int(10e9)

    def knapSack(V):
        for i in range(n + 1):
            for v in range(V + 1):
                if v == 0:
                    K[i][v] = 0
                elif val[i - 1] <= v:
                    K[i][v] = min(wt[i - 1] + K[i - 1][v - val[i - 1]], K[i - 1][v])
                else:
                    K[i][v] = K[i - 1][v]

        return K[n][V]

    n, w = mdata()
    val = [0] * (n)
    wt = [0] * (n)
    for i in range(n):
        wt[i], val[i] = mdata()
    V = 100005
    K = [[1000000007 for x in range(V + 1)] for x in range(n + 1)]
    knapSack(V)
    m = 0
    for i in range(n + 1):
        for v in range(V + 1):
            if 1 <= K[i][v] <= w:
                m = max(m, v)
    print(m)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

    INF = float('inf')
    dp = [list([INF] * (10 ** 5 + 101)) for _ in range(N)]
    dp[0][wv[0][1]] = wv[0][0]
    dp[0][0] = 0

    for i in range(1,N):
        w = wv[i][0]
        v = wv[i][1]
        for j in range(10 ** 5 + 1):
            sum_v = j + v
            if dp[i-1][j] + w <= W:
                dp[i][sum_v] = min(dp[i-1][sum_v], dp[i-1][j] + w)
            dp[i][j] = min(dp[i][j], dp[i-1][j])
    
    max_v = 0
    for i in range(10 ** 5 + 1):
        if dp[N-1][i] <= W:
            max_v = i
    print(max_v)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
  import sys
  input = sys.stdin.readline
  n,W=map(int,input().split())
  w,v=[0]*n,[0]*n
  for i in range(n):
    w[i],v[i]=map(int,input().split())
  v_sum=sum(v)
  dp=[[float('inf')]*(v_sum+1) for _ in range(n+1)]
  dp[0][0]=0
  for i in range(n):
    for j in range(v_sum+1):
      dp[i+1][j]=dp[i][j - v[i]] + w[i] if j - v[i]>=0 else dp[i+1][j]
      dp[i+1][j]=min(dp[i+1][j],dp[i][j])
  ans=0
  for j in range(v_sum+1):
    if dp[n][j] <= W:
      ans = j
  print(ans)
if __name__=='__main__':
  main()

Submission status: Accepted

Solution code:
import numpy as np
n,w=map(int,input().split())
wv=[list(map(int,input().split())) for _ in range(n)]
mv=pow(10,3)*n+1
mw=pow(10,9)*n+1
dp=np.full(mv,mw,np.int64)
# dp[i]:価値をちょうどiすることができる重さの最小値。ちょうどにできない場合dp[i]=inf。求めるのはdp[i]<=wとなるiのうち最大のもの。
dp[0]=0
for i in range(n):
      w_=wv[i][0]
      v_=wv[i][1]
      dp[v_:]=np.minimum(dp[v_:],dp[:-v_]+w_)
print(np.where(dp<=w)[-1][-1])

Submission status: Accepted

Solution code:
import sys
from io import StringIO
import unittest

def resolve():
    N, W = map(int, input().split())

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

    # 荷物の個数 * 価値上限 -> 重さ最小化
    # これだとcase2が10**9なので解けない
    inf = 10 ** 10
    max_v = sum([v for w, v in wv])+ 10
    sum_w = sum([w for w, v in wv])

    dp = [[inf for _ in range(max_v + 2)] for __ in range(N + 1)]

    # for i in range(max_v + 2):
    #     dp[0][i] = 0

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

    # ２つ目の添字を超えないように価値を選んだときの、最小の重み
    # 送るモード
    for i in range(N):
        w = wv[i][0]
        v = wv[i][1]
        for j in range(max_v + 2):
            if j - v >= 0:
                dp[i + 1][j] = min(dp[i][j], dp[i][j - v] + w)
            else:
                dp[i + 1][j] = dp[i][j]
            # if j - v >= 0:
            #     dp[i + 1][j] = min(dp[i][j], dp[i][j - v] + w)
            # elif j <= v:
            #     dp[i + 1][j] = min(dp[i][j], w)
            # else:
            #     dp[i + 1][j] = dp[i][j]

    # for d in dp:
    #     print(d)
    # print(W)
    # print([i for d in dp for i, w in enumerate(d) if w <= W])
    print(max([i for d in dp for i, w in enumerate(d) if w <= W]))


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """3 8
3 30
4 50
5 60"""
        output = """90"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """1 1000000000
1000000000 10"""
        output = """10"""
        self.assertIO(input, output)
    def test_入力例_3(self):
        input = """6 15
6 5
5 6
6 4
6 6
3 5
7 2"""
        output = """17"""
        self.assertIO(input, output)

if __name__ == "__main__":
    # unittest.main()
    resolve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import sys
from collections import defaultdict


def solve(values, _nb, max_capacity):
    dp = {}
    dp[0] = 0
    for w, v in values:
        keys = sorted(dp.keys(), reverse=True)
        for vk in keys:
            if vk + v in dp:
                dp[vk + v] = min(dp[vk + v], dp[vk] + w)
            else:
                dp[vk + v] = dp[vk] + w
    result = 0
    for v, w in dp.items():
        if w <= max_capacity and v > result:
            result = v
    return result


def solve_better(values, _nb, max_capacity):
    dp = [0] * (max_capacity + 1)
    for w, v in values:
        # dp = dp[:w] + [max(dp[j], dp[j - w] + v) for j in range(w, max_capacity + 1)]
        dp[w:] = [max(dpj, dpjw + v) for dpj, dpjw in zip(dp[w:], dp[:-w])]
    return dp[max_capacity]


def solve_slow(values, nb, max_capacity):
    dp = [[0 for _ in range(max_capacity + 1)] for _ in range(nb + 1)]
    for i in range(1, nb + 1):
        w, v = values[i - 1]
        for j in range(1, max_capacity + 1):
            if w <= j:
                dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w] + v)
            else:
                dp[i][j] = dp[i - 1][j]
    # print("\n".join(map(str, dp)))
    return dp[nb][max_capacity]


INF = pow(10, 9) * 100


def solve_errichto(values, _nb, max_capacity):
    sum_values = sum(v for _w, v in values)
    # dp[i] min total weight of items with total value exactly i
    dp = [INF] * (sum_values + 1)
    dp[0] = 0
    for w, v in values:
        for value_already in range(sum_values - v, -1, -1):
            tmp = dp[value_already] + w
            if dp[value_already + v] > tmp:
                dp[value_already + v] = tmp
    result = 0
    for v, w in enumerate(dp):
        if w <= max_capacity:
            result = max(result, v)
    return result


def do_job():
    "Do the work"
    # first line is number of test cases
    N, W = map(int, input().split())
    values = []
    for _ in range(N):
        values.append(list(map(int, input().split())))
    result = solve_errichto(values, N, W)
    print(result)


def print_output(testcase, result) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result))


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    do_job()
    return 0


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    sys.exit(main())

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    N, W = map(int, input().split())
    wv = [tuple(map(int, input().split())) for i in range(N)]

    dp = [-1]*(10**3 * N + 1)
    dp[0] = 0
    ans = 0
    for w, v in wv:
        for j in range((10**3 * N) - v, -1, -1):
            if dp[j] >= 0 and dp[j] + w <= W:
                if dp[j+v] < 0 or dp[j+v] > dp[j] + w:
                    dp[j+v] = dp[j] + w
                if ans < j+v:
                    ans = j+v
    print(ans)


main()

Submission status: Accepted

Solution code:
N,W = map(int,input().split())
wv = [map(int,input().split()) for _ in range(N)]
w,v = [list(i) for i in zip(*wv)]
max_v,max_w = 0,0
for i,j in zip(w,v):
    max_w += i
    max_v += j
dp = [[float("inf")]*(max_v+1) for _ in range(N+1)]
dp[0][0] = 0#初期値
for i in range(1,N+1):
    for j in range(max_v+1):
        if j - v[i-1] >= 0:
            dp[i][j] = min(dp[i-1][j],dp[i-1][j-v[i-1]]+w[i-1])
        else:
            dp[i][j] = dp[i-1][j]
for i in range(1,max_v+2):
    if W >= dp[N][-i]:
        print(max_v+1-i)
        break

Submission status: Accepted

Solution code:
N,W=map(int,input().split(' '))
w=[0]*N ; v=[0]*N
for i in range(N):
    w[i],v[i]=map(int,input().split(' '))
S=sum(v)
A=0
dp=[[sum(w)]*S for _ in range(N+1)]
for i in range(N):
    for j in range(S):
        if j<v[i]:
            dp[i+1][j]=min(dp[i][j],w[i])
        else:
            dp[i+1][j]=min(dp[i][j],dp[i][j-v[i]]+w[i])
        if dp[i+1][j]>W:
            A=j
            break
        if j==S-1:
          A=j+1
print(A)

Submission status: Accepted

Solution code:
import numpy as np
N,W = map(int,input().split())
dp = np.full(N*1000+1,W+1)
dp[0] = 0
for _ in range(N):
    w,v = map(int,input().split())
    np.minimum(dp[v:],dp[:-v]+w,out = dp[v:])
print(np.where(dp<=W)[0][-1])

Submission status: Accepted

Solution code:
n,w=map(int,input().split())
a=[10**10]*100001
a[0]=0
from copy import copy
c=0
for i in range(n):
    x,y=map(int,input().split())
    b=copy(a)
    c+=y
    for j in range(y,100001):
        if j<=c:
            b[j]=min(a[j-y]+x,a[j])
    a=copy(b)
l=[]
for i in range(len(a)):
    if a[i]<=w:
        l.append(i)
print(l[-1])