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^5

1 \leq w_i \leq W

1 \leq v_i \leq 10^9

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

5 5
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 2

5000000000

The answer may not fit into a 32-bit integer type.

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:
# -*- coding: utf-8 -*-
import sys

import fractions
import copy
import bisect
import math
import numpy as np
import itertools
from itertools import combinations_with_replacement
#import math#数学的計算はこれでいける。普通に0.5乗しても計算可能
#w=input()
from operator import itemgetter
from sys import stdin
#input = sys.stdin.readline#こっちの方が入力が早いが使える時に使っていこう
from operator import mul
from functools import reduce
from collections import Counter
#from collections import deque

#input = stdin.readline


j=0
k=0
n=3
r=1
a=[0]
#n=int(input())
#r=int(input())
#print(M)
#A=int(input())
#B=int(input())
#print(N)
"1行1つの整数を入力を取得し、整数と取得する"


#number_list=list(map(int, input().split(" ")))#数字の時
#print(number_list)
"12 21 332 とか入力する時に使う"
"1行に複数の整数の入力を取得し、整数として扱う"

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#メモ
for i in number_list:#こっちの方がrage使うより早いらしい
    print(number_list[i-1])#

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'''
x=[]
y=[]
for i in range(N):
    x1, y1=[int(i) for i in input().split()]
    x.append(x1)
    y.append(y1)
print(x)
print(y)
"複数行に2数値を入力する形式 x座標とy座標を入力するイメージ"
'''

'''
mixlist=[]
for i in range(N):
    a,b=input().split()
    mixlist.append((int(a),b))
print(mixlist)
"複数行にintとstrを複合して入力するやつ，今回はリスト一つで処理している"
'''

'''
#array=[input().split()for i in range(N)]
#print(type(array[0][0]))
#print(array)
"正方行列にstr型の値を入力"
'''

#brray=[list(map(int, input().split(" ")))for i in range(N)]
#print(type(brray[0][0]))
#print(brray)
'''
入力
1 2
4 5
7 8
出力結果
[[1, 2], [4, 5], [7, 8]]
'''
"列数に関して自由度の高いint型の値を入力するタイプの行列"
#以下に別解を記載
#N, M = [int(i) for i in input().split()]
'''
table = [[int(i) for i in input().split()] for m in range(m)]

print(type(N))
print(N)
print(type(M))
print(M)

print(type(table))
print(table)
'''




#s=input()
#a=[int(i) for i in s]
#print(a[0])
#print([a])
#単数値．桁ごとに分割したい．入力と出力は以下の通り
#イメージとして1桁ごとにリストに値を入れているかんじ
#intを取ると文字列分解に使える
'''
入力
1234
出力
1
[[1, 2, 3, 4]]
'''




'''
word_list= input().split(" ")
print(word_list[0])
"連続文字列の入力"
"qw er ty とかの入力に使う"
"入力すると空白で区切ったところでlistの番号が与えられる"
'''



'''
A, B, C=stdin.readline().rstrip().split()#str style 何個でもいけることが多い
print(A)
"リストではなく独立したstr型を入れるなら以下のやり方でOK"
'''


#a= stdin.readline().rstrip()
#print(a.upper())
"aという変数に入っているものを大文字にして出力"


#a,b=map(int, input().split())  #int style 複数数値入力　「A B」みたいなスペース空いた入力のとき

#なんかうまく入力されるけど
#a=[[int(i) for i in 1.strip()]for 1 in sys.stdin]
#a = [[int(c) for c in l.strip()] for l in sys.stdin]]
#print(a)
#複数行の数値を入力して正方行列を作成


##############################################################################################
##############################################################################################
#under this line explains example calculation

'''
コンビネーションの組み合わせの中身を出力する形式
for i in itertools.combinations(brray, 2)
combinationsをpermutationsにすれば順列になる
今回なら(abc133B)
入力
1 2
5 5
-2 8
出力
[[1, 2], [5, 5], [-2, 8]]
もちろん一次元リストでも使えるし
何よりiもリストのように使えるので便利
'''

#nCr combination
'''
def cmb(n,r):
    #When n < r , this function isn't valid
    r= min(n-r,r)
    #print(n,r)
    if r == 0: return 1
    over = reduce(mul, range(n, n-r, -1))
    #flochart mul(n,n-1)=x
    #next     mul(x,n-2)........(n-r+1,n-r)
    #mul read a,b and returns a*b

    under = reduce(mul, range(1, r+1))
    #print(over, under)
    #reduce is applied mul(1,2)=2
    #next   mul(2,3)=6
    #next   mul(6,4)=4.........last(r!,r+1)=r+1!

    return over // under
    #// is integer divide
    #calc example 5C2
    #over=5*4*3
    #under=3*2*1
a = cmb(n, r)
#print(a)
'''

'''
import itertools
from itertools import combinations_with_replacement

combinationについて
以下の違いを意識しよう
combinations() p, r 長さrのタプル列、ソートされた順で重複なし

combinations_with_replacement() p, r 長さrのタプル列、ソートされた順で重複あり


使用例 　　　　　　　　　　　                  出力　　
combinations('ABCD', 2)　　　　　　　　　　　　AB AC AD BC BD CD

combinations_with_replacement('ABCD', 2)　　 AA AB AC AD BB BC BD CC CD DD
'''



'''
#集計
#example
#a=[2,2,2,3,4,3,1,2,1,3,1,2,1,2,2,1,2,1]
#a=Counter(a)
for i in a.most_common(n):print(i)
#most_common()メソッドは、出現回数が多い要素順にCounterオブジェクトを並び替えます。
#引数にint型の数字nを設定した場合は、出現回数が高い上位ｎ個の要素を返します。
#何も設定しなければ、コンテナ型にあるすべての要素を出現回数の順番に並び替えたタプル型オブジェクトを返します。
#out put
#(2, 8)
 #(1, 6)
#(3, 3)
#(4, 1)
'''


#二部探索(binary search)
#A = [1, 2, 3, 3, 3, 4, 4, 6, 6, 6, 6]
#print(A)
#index = bisect.bisect_left(A, 5) # 7 最も左(前)の挿入箇所が返ってきている
#A.insert(index, 5)
#print(index)
#print(A)
'''
bisect.bisect_left(a, x, lo=0, h=len(a))
引数
a: ソート済みリスト
x: 挿入したい値
lo: 探索範囲の下限
hi: 探索範囲の上限
(lo, hiはスライスと同様の指定方法)
bisect_leftはソートされたリストaに対して順序を保ったままxを挿入できる箇所を探索します。leftが示す通り、aにすでにxが存在している場合は、挿入箇所は既存のxよりも左側になります。また、lo, hiを指定することで探索範囲を絞り込むことも可能です。デフォルトはaの全体が探索対象です。
'''





########################################################################
########################################################################
#b2=a[:]  #1次元のときはコピーはこれで良い
#print(b2)

#a= [[0]*3 for i in range(5)] #2次元配列はこう準備、[[0]*3]*5だとだめ
#b3=copy.deepcopy(a)  #2次元配列はこうコピーする
#print(b3)

def main():

    import numpy as np
    j=0
    k=0
    #n=int(input())
    #r=int(input())


    "1行1つの整数を入力を取得し、整数と取得する"
    #number_list=list(map(int, input().split(" ")))#数字の時
    #print(number_list)
    "12 21 332 とか入力する時に使う"
    "1行に複数の整数の入力を取得し、整数として扱う"
    #brray[0][0]=[weight][value]
    #print(brray)
    N, W = map(int, input().split())
    w, v = [], []
    for i in range(N):
        a, b = map(int, input().split())
        w += [a]
        v += [b]
    #i番目のwとvの値を入れこんでる
    #こうすると読み込みもスムーズ
    #print(max(dp[n][:]))
    DP = np.zeros(W+1, dtype=int)
    #dpp   = np.zeros(10, dtype = int)#一列のリスト
    #22exでは行けるのになぜエラーが出る?
    #wの大文字小文字ミス
    #print(DP)ちゃんとw+1行出来てる
    #print(DP)
    for i in range(N):
        DP[w[i]:] = np.maximum(DP[:-w[i]]+ v[i], DP[w[i]:])
        #DP[w[i]:]はおもさw[i]以上のdpが入る部分を指している
        #[:-w[i]]ってのはdpの
        #print(DP)
        #print(DP[:-w[i]]+ v[i], DP[w[i]:])
        #print(w[i])
        #print(DP[:-w[i]])#一番左端からから右からw[i]番目まで考えるということか
        #そうすれば必ずw[i]のものを袋に入れることができる賢い
        #print("DP",DP)
        #print("DP[w[i]:]",DP[w[i]:])

        #i+1番目を求める時i番目があればよいのでこうなってる
    print(DP[-1])
    #print(dp)#最終列がn+1列目であることに注意
    #s=input()
    #a=[int(i) for i in s]#int取るとstrでも行ける
    #print(a)
    '''
    入力
    1234
    出力
    [1, 2, 3, 4]
    '''



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, W = map(int, input().split())
Weight = [0]
Value = [0]

for i in range(N):
    w, v = map(int, input().split())
    Weight.append(w)
    Value.append(v)

DP = [[0]*(W+1) for i in range(N+1)]
for n in range(1, N + 1):
    for wei in range(W+1):
        if Weight[n] > wei:
            DP[n][wei] = DP[n-1][wei]
        else:
            DP[n][wei] = max(DP[n-1][wei], DP[n-1][wei - Weight[n]] + Value[n])
print(DP[N][W])

Submission status: Accepted

Solution code:
N,W = map(int,input().split())
weight = []
value = []
for i in range(N):
    w,v = map(int,input().split())
    weight.append(w)
    value.append(v)
dp = [[0 for i in range(W+1)] for j in range(N+1)]
for i in range(1,N+1):
    for j in range(1,W+1):
        op1,op2 = 0,0
        if weight[i-1] <= j:
            op1 = value[i-1] + dp[i-1][j-weight[i-1]]
        op2 = dp[i-1][j]
        dp[i][j] = max(op1,op2)
print(dp[N][W])

Submission status: Accepted

Solution code:
n, w = map(int, input().split())
items = [list(map(int, input().split())) for _ in range(n)]
max_w = w + 1

dp = [[float('inf')] * max_w for _ in range(n)]

for sum_w in range(max_w):
    if sum_w + items[0][0] < max_w:
        dp[0][sum_w] = items[0][1]
    else:
        dp[0][sum_w] = 0

for i in range(1, n):
    for sum_w in range(max_w):
        if sum_w + items[i][0] < max_w:
            v_0 = dp[i-1][sum_w + items[i][0]] + items[i][1]
            v_1 = dp[i-1][sum_w]
            dp[i][sum_w] = max(v_0, v_1)
        else:
            dp[i][sum_w] = dp[i-1][sum_w]
print(dp[n-1][0])

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

def chmax(a, b):
    if a >= b:
        return a
    else:
        return b

dp = [[0]*(10**5 + 10) for _ in range(110)]

#i個の品物を入れて重さがjになっているときの価値の総和の最大値
#dp[i+1][j] = dp[i][j - w[i] + v[i]] 入れるとき
#dp[i+1][j] = dp[i][j] 入れないとき

#dp[0][j] = 0 初期値設定でOK
for i in range(N+1):
    for j in range(W+1):
        dp[i+1][j] = chmax(dp[i+1][j], dp[i][j])
        if (i < N):
            if (j >= w[i]):
                dp[i+1][j] = chmax(dp[i+1][j], dp[i][j - w[i]] + v[i])

print(dp[N][W])

Submission status: Accepted

Solution code:
a=input().split()
N=int(a[0])
W=int(a[1])
wv_list=[]
for i in range(N) :
  b=input().split()
  w=int(b[0])
  v=int(b[1])

  wv_list.append([w,v])

n_list=  [[0 for i in range(W+1)] for j in range(N)]


if wv_list[0][0]<=W :
    n_list[0][wv_list[0][0]]=wv_list[0][1]

for i in range(1,N) :
    for j in range(W) :
        s=j+wv_list[i][0]
        if s<=W :
            n_list[i][s]=max(n_list[i-1][j]+wv_list[i][1],n_list[i][s])

        n_list[i][j] = max(n_list[i - 1][j],n_list[i][j])

print(max(n_list[-1]))

Submission status: Accepted

Solution code:
def main():
    import numpy as np
    N, W = map(int, input().split())
    ndp = np.zeros(W+1, dtype= np.int64)
    for _ in range(N):
        w, v = map(int,input().split())
        np.maximum(ndp[:-w] + v, ndp[w:], out = ndp[w:])
    else:print(ndp[-1])

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
import sys
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
N,W = LI()
dp = [0 for _ in range(W+1)]
for i in range(1,N+1):
    w,v = LI()
    for j in range(W,0,-1):
        if j < w: continue
        dp[j] = max(dp[j],dp[j-w]+v)
print(dp[-1])

Submission status: Accepted

Solution code:
N,W=map(int,input().split())
WV=[list(map(int,input().split())) for i in range(N)]
import numpy as np
dp=np.zeros(W+1,dtype=np.int64)
for w,v in WV:
    dp[w:]=np.maximum(dp[w:],dp[:-w]+v)
print(max(dp))

Submission status: Accepted

Solution code:
n, w = map(int, input().split())
goods = [list(map(int, input().split())) for _ in range(n)]
dp = [[0] * (w + 1) for _ in range(n + 1)]

for i in range(n):
    weight, value = goods[i]
    for sum_w in range(w + 1):
        if (sum_w - weight) >= 0:
            dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w - weight] + value)

        dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w])

print(dp[n][w])

Submission status: Accepted

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

n, w = map(int, input().split())
item = [list(map(int, input().split())) for _ in range(n)]
dp = [[0] + [0]*w] + [[-float("inf")]*(w+1) for _ in range(n)]
wei, val = 0, 1

for i in range(n):
    for j in range(w+1):
        if item[i][wei] <= j:
            dp[i+1][j] = max(dp[i][j], dp[i][j-item[i][wei]] + item[i][val])
        else:
            dp[i+1][j] = dp[i][j]

print(dp[n][w])

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)

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

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

print(dp[N][W])

Submission status: Accepted

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


def solve(N: int, W: int, w: "List[int]", v: "List[int]"):
    dp = [[0] * (W+1) for _ in range(N+1)]
    for i in range(N):
        for j in range(1, W+1):
            if j - w[i] >= 0:
                dp[i+1][j] = max(
                    dp[i][j],
                    dp[i+1][j-1],
                    dp[i][j-w[i]] + v[i]
                )
            else:
                dp[i+1][j] = max(dp[i][j], dp[i+1][j-1])

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


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:
import numpy as np
def resolve():
    n, w = map(int, input().split())
    goods = np.array([list(map(int, input().split())) for _ in range(n)])
    
    # dpテーブルを1次元にして破壊的に更新していくパターン
    dp = np.zeros([w + 1], dtype=int)

    for i in range(1, n + 1):
        tmp = np.zeros(w + 1, dtype=int)
        tmp[goods[i - 1][0]:] = dp[:-goods[i - 1][0]] + goods[i - 1][1]
        dp = np.maximum(dp, tmp)

    print(dp[w])
    
resolve()

Submission status: Accepted

Solution code:
import numpy as np
def resolve():
    n, w = map(int, input().split())
    goods = np.array([list(map(int, input().split())) for _ in range(n)])
    dp = np.zeros([n + 1, w + 1], dtype=int)

    for i in range(1, n + 1):
        tmp = np.zeros(w + 1, dtype=int)
        tmp[goods[i - 1][0]:] = dp[i - 1][:-goods[i - 1][0]] + goods[i - 1][1]
        dp[i] = np.maximum(dp[i - 1], tmp)

    print(dp[n][w])
    
resolve()

Submission status: Accepted

Solution code:
def resolve():
    n, w = map(int, input().split())
    goods = [list(map(int, input().split())) for _ in range(n)]
    dp = [[0] * (w + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(w + 1):
            tmp = dp[i - 1][j - goods[i - 1][0]] + goods[i - 1][1] if j >= goods[i - 1][0] else 0
            dp[i][j] = max(dp[i - 1][j], tmp)

    print(dp[n][w])
    
resolve()

Submission status: Accepted

Solution code:
def resolve():
    n, w = map(int, input().split())
    goods = [list(map(int, input().split())) for _ in range(n)]
    dp = [[0] * (w + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in reversed(range(w + 1)):
            tmp = dp[i - 1][j - goods[i - 1][0]] + goods[i - 1][1] if j >= goods[i - 1][0] else 0
            dp[i][j] = max(dp[i - 1][j], tmp)

    print(dp[n][w])

resolve()

Submission status: Accepted

Solution code:
def resolve():
    n, w = map(int, input().split())
    goods = [list(map(int, input().split())) for _ in range(n)]

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

    for i in range(1, n + 1):
        for j in reversed(range(w + 1)):
            # もしi番目の品物が入るのであれば
            if goods[i - 1][0] <= j:
                dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - goods[i - 1][0]] + goods[i - 1][1])
            else:
                dp[i][j] = dp[i - 1][j]

    print(dp[n][w])
    
resolve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
import sys
from collections import Counter
from itertools import permutations, combinations
from fractions import gcd
#from math import gcd
from math import ceil, floor
import bisect
sys.setrecursionlimit(10 ** 6)
inf = float("inf")

def chmin(a, b):
    if a > b:
        return b
    else:
        return a

def chmax(a, b):
    if a < b:
        return b
    else:
        return a

def input():
    return sys.stdin.readline()[:-1]

def main():
    n, w = map(int, input().split())
    wv = [tuple(map(int, input().split())) for _ in range(n)]
    dp = [[0] * (w+1) for _ in range(n+1)]

    for i in range(n):
        for sum_w in range(w+1):
            if (sum_w - wv[i][0] >= 0):
                dp[i+1][sum_w] = chmax(dp[i+1][sum_w], dp[i][sum_w - wv[i][0]] + wv[i][1])

            dp[i+1][sum_w] = chmax(dp[i+1][sum_w], dp[i][sum_w])

    print(dp[n][w])

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
import numpy as np

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

dp = np.zeros(W+1 , np.int64)


for i in range(N):
    w,v = map(int, input().split())
    dp[w:] = np.maximum(dp[w:] , dp[:-w] + v)

print(dp[-1])

Submission status: Accepted

Solution code:
n, w = map(int, input().split())
dp = [[0 for _ in range(w+1)] for _ in range(n+1)]
ws, vs = [], []
for _ in range(n):
    wi, vi = map(int, input().split())
    ws.append(wi)
    vs.append(vi)
for i in range(n):
    for j in range(1, w+1):
        if j - ws[i] >= 0:
            dp[i + 1][j] = max(dp[i][j], dp[i][j - ws[i]] + vs[i])
        else:
            dp[i+1][j] = dp[i][j]
print(dp[-1][-1])

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()
dp = [[0] * (k+1) for i in range(n+1)]
for i in range(n):
    w, v = inpl()
    for j in range(k + 1):
        include = dp[i][j - w] + v if j >= w else 0
        not_include = dp[i][j]
        dp[i + 1][j] = max(include, not_include)
print(max(dp[n][:]))
# for i in dp:
#     print(i)

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

dp = np.zeros((N+1, W+1), np.int64)

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

print(np.amax(dp[N]))

Submission status: Accepted

Solution code:
N, W = map(int, (input().split()))
lst = [list(map(int, input().split())) for i in range(N)]

ans = [[0]*(10**5+10) for i in range(N+10)]
  
for i in range(N):
  for j in range(W+1):
    if j >= lst[i][0]:
      ans[i+1][j] = max(ans[i][j-lst[i][0]] + lst[i][1], ans[i][j])
    else:
      ans[i+1][j] = ans[i][j]
  
print(ans[N][W])

Submission status: Accepted

Solution code:
import numpy as np

N, W = map(int, input().split())
dp = np.zeros(W + 1, np.int64)
for _ in range(N):
    w, v = map(int, input().split())
    dp[w:] = np.maximum(dp[w:], dp[:-w] + v)
print(dp[W])

Submission status: Accepted

Solution code:
[N,W]=[int(i) for i in input().split()]
WV=[]
for i in range(N):
	WV+=[[int(j) for j in input().split()]]
DP=[[0 for i in range(W+1)]for j in range(N)]
for i in range(N):
	for sum_w in range(W+1):
		if sum_w>=WV[i][0]:
			DP[i][sum_w]=max(DP[i-1][sum_w],DP[i-1][sum_w-WV[i][0]]+WV[i][1])
		else:
			DP[i][sum_w]=DP[i-1][sum_w]
print(DP[N-1][W])

Submission status: Accepted

Solution code:
[n,w] = [int(i) for i in input().split()]
dp = [[0]*(w+1) for i in range(n)]
wv = []
for i in range(n):
    wv.append([int(j) for j in input().split()])
"""
dp[i][w] = v
i : i番目まで
w : それまでの合計
"""

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

Submission status: Accepted

Solution code:
N,W=map(int,input().split())
dp=[[0]*(W+1) for _ in range(N+1)]
for i in range(N):
  w,v=map(int,input().split())
  for j in range(W+1):
    if j-w>=0:
      dp[i+1][j]=max(dp[i][j],dp[i][j-w]+v)
    else:
      dp[i+1][j]=dp[i][j]
print(max(dp[N]))

Submission status: Accepted

Solution code:
# @oj: atcoder
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-04-30 11:24
# @url:https://atcoder.jp/contests/dp/tasks/dp_d
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
# region fastio

BUFSIZE = 8192

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = 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(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")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def main():
    nv=list(map(int,input().split()))
    n,v=nv[0],nv[1]
    wc=[list(map(int,input().split())) for i in range(n)]
    w=[x[0] for x in wc]
    c=[x[1] for x in wc]
    dp=[[0]*(v+1) for i in range(n+1)]
    for i in range(1,n+1):
        for j in range(v+1):
            if j>=w[i-1]:
                dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i-1]]+c[i-1])
            else:
                dp[i][j]=dp[i-1][j]
        # print (dp)
    print (dp[n][v])
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, W = list(map(int, input().split(" ")))
dp =  [[0] * (W+1) for _ in range(N+1)]
 
for i in range(0, N):
	weight, value = map(int, input().split(" "))
	for w in range(1, W+1):
		if w >= weight:
			dp[i + 1][w] = max([dp[i][w - weight] + value, dp[i][w]])
		else:
			dp[i + 1][w] = dp[i][w]
print(dp[N][W])

Submission status: Accepted

Solution code:
n,w=map(int,raw_input().split())
a=[map(int,raw_input().split()) for _ in xrange(n)]
z=[[0]*(w+1)]
for i in xrange(n):
    z.append(z[-1][:])
    for j in xrange(w+1):
        if a[i][0]<=j:
            z[i+1][j]=max(z[i+1][j],z[i][j-a[i][0]]+a[i][1])
print max(z[-1])

Submission status: Accepted

Solution code:
import numpy as np

N, W = map(int, input().split())
dp = np.zeros(W + 1, np.int64)
for _ in range(N):
    w, v = map(int, input().split())
    np.maximum(dp[w:], dp[:-w] + v, out=dp[w:])
print(dp[W])

Submission status: Accepted

Solution code:
import numpy as np
n,w=map(int,input().split())
dp=np.zeros(w+1,dtype=np.int64)
for _ in range(n):
    we,v=map(int,input().split())
    np.maximum(dp[we:],dp[:-we]+v,out = dp[we:])
print(dp[w])

Submission status: Accepted

Solution code:
import numpy as np
n,w=map(int,input().split())
dp=np.zeros(w+1,dtype=np.int64)
for _ in range(n):
    we,v=map(int,input().split())
    if we > w:
        continue
    else:
        np.maximum(dp[we:],dp[:-we]+v,out = dp[we:])
print(dp[w])

Submission status: Accepted

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

dp = [0]*(max_w+1)
dp = np.array(dp)

for _ in range(n):
    w, v = map(int, input().split())
    np.maximum(dp[:-w] + v, dp[w:], out=dp[w:])

print(max(dp))

Submission status: Accepted

Solution code:
n,maxw=map(int,input().split())
nap=[0]*n
for i in range(n):
    nap[i]=list(map(int,input().split()))
dp=[[0]*(maxw+1) for _ in range(n)]
for i in range(n):
    for j in range(maxw+1):
        if nap[i][0]>j:
            dp[i][j]=dp[i-1][j]
        else:
            dp[i][j]=max(dp[i-1][j],dp[i-1][j-nap[i][0]]+nap[i][1])
print(dp[n-1][maxw])

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

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

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

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

Submission status: Accepted

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

dp = [0]*(W+1)

for w, v in wv:
    newdp = dp[:]
    for ww in range(W+1):
        if w+ww > W:
            continue
        newdp[w+ww] = max(dp[ww+w], dp[ww]+v)
    dp = newdp

print(dp[-1])

Submission status: Accepted

Solution code:
N, W = map(int, input().split())
weight = []
value = []
for i in range(N):
    w, v = map(int, input().split())
    weight.append(w)
    value.append(v)
dp = [[0] * (W + 1) for _ in range(N + 1)]
for i in range(N):
    for sum_w in range(W + 1):
        if sum_w - weight[i] >= 0:
            dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i]
                                   [sum_w - weight[i]] + value[i])
        dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w])

print(dp[N][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)
dp = list([0] * (max_weight + 1) for _ in range(n + 1))
for i in range(n):
    for w in range(1, max_weight + 1):
        if w >= W[i]:
            dp[i + 1][w] = max(dp[i][w], dp[i][w - W[i]] + V[i])
        else:
            dp[i + 1][w] = dp[i][w]

print(dp[n][max_weight])

Submission status: Accepted

Solution code:
import numpy as np

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

dp = np.zeros(W + 1, dtype=np.int64)
for n in range(N):
    tmp = np.zeros_like(dp, dtype=np.int64)
    tmp[goods[n][0]:] = dp[:W + 1 - goods[n][0]] + goods[n][1]
    dp = np.maximum(dp, tmp)
print(dp[W])

Submission status: Accepted

Solution code:
def knapsack(sizes, vals, volume):
    n = len(sizes)

    # dp[i][j] is the max value at item i while using capacity j
    dp = [[0] * (volume+1) for _ in range(n)] # j is 0...volume

    for i in range(n):
        for j in range(volume+1):
            dp[i][j] = max(dp[i][j], dp[i-1][j])
            if j - sizes[i] >= 0:
                dp[i][j] = max(dp[i][j], dp[i-1][j-sizes[i]] + vals[i])

    return dp[-1][-1]


if __name__ == "__main__":
    n, volume = [int(x) for x in input().split()]
    sizes, vals = [], []
    for _ in range(n):
        s, v = [int(x) for x in input().split()]
        sizes.append(s)
        vals.append(v)
    print(knapsack(sizes, vals, volume))

Submission status: Accepted

Solution code:
def main():
    N, W = map(int, input().split())
 
    dp = [-1] * (W + 1)
    dp[0] = 0
    for _ in range(N):
        w, v = map(int, input().split())
        for i in range(W - w, -1, -1):
            if dp[i] == -1:
                continue
            if dp[i + w] < dp[i] + v:
                dp[i + w] = dp[i] + v
    print(max(dp))
 
 
main()

Submission status: Accepted

Solution code:
def knapsack(sizes, vals, volume):
    n = len(sizes)

    dp = [[0] * (volume+1) for _ in range(n)] # j is 0...volume

    for i in range(n):
        for j in range(volume+1):
            dp[i][j] = max(dp[i][j], dp[i-1][j])
            if j - sizes[i] >= 0:
                dp[i][j] = max(dp[i][j], dp[i-1][j-sizes[i]] + vals[i])
            #dp[i][j] = max(dp[i][j], dp[i-1][j])

    return dp[-1][-1]


if __name__ == "__main__":
    n, volume = [int(x) for x in input().split()]
    sizes, vals = [], []
    for _ in range(n):
        s, v = [int(x) for x in input().split()]
        sizes.append(s)
        vals.append(v)
    print(knapsack(sizes, vals, volume))

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 = []
for i in range(N):
    weight, value = map(int, readline().split())
    things.append((weight, value))


def solve():
    dp = np.zeros(W + 1, dtype=int)
    w0, v0 = things[0]
    dp[w0:] = v0
    for i in range(1, N):
        weight, value = things[i]
        np.maximum(dp[weight:], dp[:-weight] + value, out=dp[weight:])
    return dp[W]


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

Submission status: Accepted

Solution code:
n,w=map(int,input().split())
wv=[list(map(int,input().split())) for _ in range(n)]
wv.sort()
cost=[[0]*(w+1) for _ in range(n+1)]
for i in range(1,n+1):
    for j in range(w+1):
        if wv[i-1][0] <= j:
            cost[i][j]=max(wv[i-1][1]+cost[i-1][j-wv[i-1][0]],cost[i-1][j])
        else:
            cost[i][j]=cost[i-1][j]
print(cost[n][w])

Submission status: Accepted

Solution code:
def solve(items, w):
    dp = [[0]*(w+1)]
    for item in items:
        curr = []
        for i in range(w+1):
            if i - item[0] >= 0:
                curr.append(max(dp[-1][i], dp[-1][i - item[0]]+item[1]))
            else:
                curr.append(dp[-1][i])
        dp.append(curr)
    return dp[-1][-1]


if __name__ == "__main__":
    n, w = map(int, input().split())
    items = [[int(x) for x in input().split()] for y in range(n)]
    print(solve(items, w))

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)

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

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

print(dp[N][W])

Submission status: Accepted

Solution code:
import numpy as np
N, W = map(int, input().split())
dp = np.zeros((N+1, W+1), dtype=int)

w,v = [],[]
for _ in range(N):
    w_,v_ = map(int,input().split())
    w.append(w_)
    v.append(v_)

for row in range(N):
    dp[row+1,:w[row]] = dp[row,:w[row]]
    dp[row+1,w[row]:] = np.maximum(dp[row,w[row]:],v[row]+dp[row,:-w[row]])

print(dp[N,-1])