Problem:
 Score : 400 points    Problem Statement You have N items and a bag of strength W .
The i -th item has a weight of w_i and a value of v_i .  You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most W .  Your objective is to maximize the total value of the selected items.      Constraints  1 ≤ N ≤ 100  1 ≤ W ≤ 10^9  1 ≤ w_i ≤ 10^9  For each i = 2,3,...,N , w_1 ≤ w_i ≤ w_1 + 3 .  1 ≤ v_i ≤ 10^7  W , each w_i and v_i are integers.         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 total value of the selected items.        Sample Input 1 4 6
2 1
3 4
4 10
3 4      Sample Output 1 11  The first and third items should be selected.       Sample Input 2 4 6
2 1
3 7
4 10
3 6      Sample Output 2 13  The second and fourth items should be selected.       Sample Input 3 4 10
1 100
1 100
1 100
1 100      Sample Output 3 400  You can take everything.       Sample Input 4 4 1
10 100
10 100
10 100
10 100      Sample Output 4 0  You can take nothing.

Solution (Python):
import copy

N, W = map(int, input().split())
wvl = []
first_w, v = map(int, input().split())
wvl.append((first_w,v))
for _ in range(N-1):
    w,v = map(int, input().split())
    
    wvl.append((w,v))

w_set_res = set()
w_set = set()
w_set_res.add(0)
w_set.add(0)
for i in range(N-1):
    next_w_set = set()
    for w in list(w_set):
        for j in range(0,4):
            new_w = w+j+first_w
            if new_w <= W:
                next_w_set.add(new_w)
                w_set_res.add(new_w)
    w_set = copy.deepcopy(next_w_set)

w_set_res.add(0)

w_list = list(w_set_res)
w_list.sort()

max_w = min(4*N, W-first_w*N)
dp = [ {0:0} for _ in range(N+1)]
for d in dp:
    for w in w_list:
        d[w] = 0

for i in range(N):
    wi,vi = wvl[i]
    for w in w_list:
        if w-wi in w_set_res:
            dp[i+1][w] = max(dp[i][w-wi] + vi, dp[i][w])
        else:
            dp[i+1][w] = dp[i][w]


print(max(dp[N].values()))

Solution (Python):
N,W=map(int,input().split())
A=[]
W1,W2,W3,W4=[],[],[],[]
for i in range(N):
  w,v=map(int,input().split())
  if i==0:
    a=w
  A.append((v,w))
  if w-a==0:
    W1.append(v)
  elif w-a==1:
    W2.append(v)
  elif w-a==2:
    W3.append(v)
  else:
    W4.append(v)
  

W1,W2,W3,W4=sorted(W1)[::-1],sorted(W2)[::-1],sorted(W3)[::-1],sorted(W4)[::-1]

l1,l2,l3,l4=len(W1),len(W2),len(W3),len(W4)
ans=0
for i in range(l1+1):
  for j in range(l2+1):
    for k in range(l3+1):
      for l in range(l4+1):
        value=sum(W1[:i])+sum(W2[:j])+sum(W3[:k])+sum(W4[:l])
        if a*i+(a+1)*j+(a+2)*k+(a+3)*l<=W:
          ans=max(ans,value)
print(ans)

Solution (Python):
N,W=map(int,input().split())
A=[]
W1,W2,W3,W4=[],[],[],[]
for i in range(N):
  w,v=map(int,input().split())
  if i==0:
    a=w
  A.append((v,w))
  if w-a==0:
    W1.append(v)
  elif w-a==1:
    W2.append(v)
  elif w-a==2:
    W3.append(v)
  else:
    W4.append(v)
  

W1,W2,W3,W4=sorted(W1)[::-1],sorted(W2)[::-1],sorted(W3)[::-1],sorted(W4)[::-1]

l1,l2,l3,l4=len(W1),len(W2),len(W3),len(W4)
ans=0
for i in range(l1+1):
  for j in range(l2+1):
    for k in range(l3+1):
      for l in range(l4+1):
        value=sum(W1[:i])+sum(W2[:j])+sum(W3[:k])+sum(W4[:l])
        if a*i+(a+1)*j+(a+2)*k+(a+3)*l<=W:
          ans=max(ans,value)
print(ans)

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

minw = min(w)
for i in range(N):
    w[i] -= minw

ww = [[] for _ in range(4)]
for i, o in enumerate(w):
    ww[o].append(v[i])
for i in range(4):
    ww[i].sort(reverse=True)

ans = 0
for i in range(len(ww[0])+1):
    isum = sum(ww[0][:i])
    for j in range(len(ww[1])+1):
        jsum = sum(ww[1][:j])
        for k in range(len(ww[2])+1):
            ksum = sum(ww[2][:k])
            for t in range(len(ww[3])+1):
                tsum = sum(ww[3][:t])
                weight = minw * i + (minw+1) * j + (minw+2) * k + (minw+3) * t
                if weight <= W:
                    ans = max(ans, isum+jsum+ksum+tsum)
print(ans)

Solution (Python):
N, W = map(int, input().split())
wv = []
w0 = []
w1 = []
w2 = []
w3 = []
for i in range(N):
    wv.append(list(map(int, input().split())))
wv.sort(key=lambda x:(x[0], -x[1]))

wbase = wv[0][0]
for w, v in wv:
    if(w == wbase):
        w0.append(v)
    elif(w == wbase+1):
        w1.append(v)
    elif(w == wbase+2):
        w2.append(v)
    else:
        w3.append(v)
        
sw0, sw1, sw2, sw3 = [0], [0], [0], [0]
s = 0
for v in w0:
    s += v
    sw0.append(s)
s = 0
for v in w1:
    s += v
    sw1.append(s)
s = 0
for v in w2:
    s += v
    sw2.append(s)
s = 0
for v in w3:
    s += v
    sw3.append(s)
    
value = 0
ans = 0
for i in range(len(sw0)):
    if(wbase*i > W):
        break
    for j in range(len(sw1)):
        if(wbase*i+(wbase+1)*j > W):
            break
        for k in range(len(sw2)):
            if(wbase*i+(wbase+1)*j+(wbase+2)*k > W):
                break
            for l in range(len(sw3)):
                if(wbase*i+(wbase+1)*j+(wbase+2)*k+(wbase+3)*l > W):
                    break
                value = sw0[i]+sw1[j]+sw2[k]+sw3[l]
                ans = max(ans, value)        
print(ans)

Solution (Python):
N, W = map(int, input().split())
wv = list(map(int, input().split()))
w1 = wv[0]

wvs = [[] for i in range(4)]
wvs[0].append(wv[1])

for i in range(N - 1):
  w, v = list(map(int, input().split()))
  w -= w1
  wvs[w].append(v)

s = [0] * 4
for i in range(4):
  wvs[i] = sorted(wvs[i], reverse = True)
  s[i] = len(wvs[i])
  if s[i] > 1:
    for j in range(1, s[i]):
      wvs[i][j] += wvs[i][j - 1]
  wvs[i].insert(0, 0)


ans = 0
for i in range(s[0] + 1):
  for j in range(s[1] + 1):
    for k in range(s[2] + 1):
      for l in range(s[3] + 1):
        weight = w1 * (i + j + k + l) + (j + 2 * k + 3 * l)
        if weight <= W:
          value = wvs[0][i] + wvs[1][j] + wvs[2][k] + wvs[3][l]
          ans = max(ans, value)
          
print(ans)

Solution (Python):
N, W = map(int, input().split())
wv = list(map(int, input().split()))
w1 = wv[0]

wvs = [[] for i in range(4)]
wvs[0].append(wv[1])

for i in range(N - 1):
  w, v = list(map(int, input().split()))
  w -= w1
  wvs[w].append(v)

s = [0] * 4
for i in range(4):
  wvs[i] = sorted(wvs[i], reverse = True)
  s[i] = len(wvs[i])
  if s[i] > 1:
    for j in range(1, s[i]):
      wvs[i][j] += wvs[i][j - 1]
  wvs[i].insert(0, 0)


ans = 0
for i in range(s[0] + 1):
  for j in range(s[1] + 1):
    for k in range(s[2] + 1):
      for l in range(s[3] + 1):
        weight = w1 * (i + j + k + l) + (j + 2 * k + 3 * l)
        if weight <= W:
          value = wvs[0][i] + wvs[1][j] + wvs[2][k] + wvs[3][l]
          ans = max(ans, value)
          
print(ans)

Solution (Python):
from itertools import accumulate, product
def solve():
    N,W = map(int,input().split())
    value = [list() for _ in range(4)]
    w1 = None
    for i in range(N):
        w,v = map(int,input().split())
        if i == 0:
            w1 = w
        value[w-w1].append(v)
    
    acc = []
    for i in range(4):
        value[i].sort(reverse=True)
        acc.append(list(accumulate(value[i])))
    
    comb = []
    for i_0 in range(len(acc[0]) + 1):
        for i_1 in range(len(acc[1]) + 1):
            for i_2 in range(len(acc[2]) + 1):
                for i_3 in range(len(acc[3]) + 1):
                    comb.append((i_0,i_1,i_2,i_3))
    ans = 0
    for c in comb:
        if isOver(c, acc):
            continue
        sum_w = c[0] * w1 + c[1] * (w1+1) + c[2] * (w1+2) + c[3] * (w1+3)
        if sum_w > W:
            continue
        res = 0
        for i in range(4):
            if c[i] == 0:
                continue
            res += acc[i][c[i]-1]
        
        ans = max(ans,res)
    
    print(ans)

def isOver(c, acc):
    res = False
    for i in range(4):
        if len(acc[i]) < c[i]:
            res = True
    
    return res
if __name__ == '__main__':
    solve()

Solution (Python):
N,W=map(int,input().split())
a,b=map(int,input().split())
w0=[b]
w1=[]
w2=[]
w3=[]
for i in range(N-1):
    w,v=map(int,input().split())
    if w-a==0:
        w0.append(v)
    elif w-a==1:
        w1.append(v)
    elif w-a==2:
        w2.append(v)
    else:
        w3.append(v)
w0=sorted(w0,reverse=True)
w1=sorted(w1,reverse=True)
w2=sorted(w2,reverse=True)
w3=sorted(w3,reverse=True)
ans=0
for i in range(max(len(w0)+1,1)):
    for j in range(max(len(w1)+1,1)):
        for k in range(max(len(w2)+1,1)):
            for l in range(max(len(w3)+1,1)):
                if a*i+(a+1)*j+(a+2)*k+(a+3)*l<=W:
                    lst=w0[:i]+w1[:j]+w2[:k]+w3[:l]
                    ans=max(sum(lst),ans)
print(ans)

Solution (Python):
N,W=map(int,input().split())
w1,v=map(int,input().split())
if w1>W:
    print(0)
    exit()
lst=[[-1]*(3*N-2) for _ in range(N)]
lst[0][0]=v
for i in range(N-1):
    w,v=map(int,input().split())
    for j in range(N-1,-1,-1):
        for k in range(3*N-2):
            if lst[j][k]!=-1:
                if (j+1)*w1+k+w<=W:
                    lst[j+1][k+w-w1]=max(lst[j][k]+v,lst[j+1][k+w-w1])
    lst[0][w-w1]=max(v,lst[0][w-w1])

lst=[i for j in lst for i in j]
print(max(lst))

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

W1,V1 = map(int, input().split())

P = {W1:[V1], W1+1:[], W1+2:[], W1+3:[]}

for i in range(1,N):
  w,v = map(int, input().split())
  P[w].append(v)

PS={}
for k,v in P.items():
  v.sort(reverse=True)
  S = [0] * (len(v)+1)
  for i in range(len(v)):
    S[i+1] = S[i] + v[i]
  PS[k] = S
  


A,B,C,D = len(PS[W1]), len(PS[W1+1]), len(PS[W1+2]), len(PS[W1+3])
ans = 0
for a in range(A):
  for b in range(B):
    for c in range(C):
      for d in range(D):
        if a*W1 + b*(W1+1) + c*(W1+2) + d*(W1+3) > W:
          continue
        ans = max(ans, PS[W1][a] + PS[W1+1][b] + PS[W1+2][c] + PS[W1+3][d])
        
print(ans)

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from itertools import accumulate

    n, k = map(int, readline().split())
    item = [[] for _ in range(4)]
    cnt = [0] * 4

    w, v = map(int, readline().split())
    first = w
    item[0].append(v)
    cnt[0] += 1

    for i in range(n - 1):
        w, v = map(int, readline().split())
        item[w - first].append(v)
        cnt[w - first] += 1

    for i in range(4):
        item[i].sort(reverse=True)

    acc = [[0] + list(accumulate(item[i])) for i in range(4)]

    ans = 0
    for p in range(cnt[0] + 1):
        for q in range(cnt[1] + 1):
            for r in range(cnt[2] + 1):
                for s in range(cnt[3] + 1):
                    weight = (p + q + r + s) * first + q + 2 * r + 3 * s
                    if weight > k:
                        break
                    value = acc[0][p] + acc[1][q] + acc[2][r] + acc[3][s]
                    ans = max(ans, value)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
n,W=map(int,input().split())

v1=[]
v2=[]
v3=[]
v4=[]

w,v=map(int,input().split())
v1.append(v)
w1=w

for _ in range(n-1):
    w,v=map(int,input().split())
    if w1==w:
        v1.append(v)
    elif w1+1==w:
        v2.append(v)
    elif w1+2==w:
        v3.append(v)
    elif w1+3==w:
        v4.append(v)

v1.sort(reverse=True)
v2.sort(reverse=True)
v3.sort(reverse=True)
v4.sort(reverse=True)

v=[v1,v2,v3,v4]

sumv=[[] for _ in range(4)]

for i,item in enumerate(v):
    tmp=[0]
    tmpv=0
    for j in item:
        tmpv+=j
        tmp.append(tmpv)
    sumv[i]=tmp

ans=0

for num1 in range(len(sumv[0])):
    for num2 in range(len(sumv[1])):
        for num3 in range(len(sumv[2])):
            for num4 in range(len(sumv[3])):

                tmpans=0
                tmpwait=0
                if sumv[0][num1]!=0:
                    tmpans+=sumv[0][num1]
                    tmpwait+=(num1)*(w1)
                if sumv[1][num2]!=0:
                    tmpans+=sumv[1][num2]
                    tmpwait+=(num2)*(w1+1)
                if sumv[2][num3]!=0:
                    tmpans+=sumv[2][num3]
                    tmpwait+=(num3)*(w1+2)
                if sumv[3][num4]!=0:
                    tmpans+=sumv[3][num4]
                    tmpwait+=(num4)*(w1+3)

                if tmpwait<=W:
                    ans=max(ans,tmpans)

print(ans)

Solution (Python):
n,w=map(int,input().split())
kind=[[] for _ in range(4)]
for i in range(n):
    w_,v=map(int,input().split())
    if i==0:
        stan=w_
    kind[w_-stan].append(v)
for i in range(4):
    kind[i].sort(reverse=True)
    if len(kind[i])>=2:
        for j in range(len(kind[i])-1):
            kind[i][j+1]+=kind[i][j]
    kind[i]=[0]+kind[i]
ans=0
for i in range(len(kind[0])):
    for j in range(len(kind[1])):
        for k in range(len(kind[2])):
            for l in range(len(kind[3])):
                if stan*i+(stan+1)*j+(stan+2)*k+(stan+3)*l<=w:
                    ans=max(ans,kind[0][i]+kind[1][j]+kind[2][k]+kind[3][l])
print(ans)

Solution (Python):




import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial,sqrt
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,w=MI()
lis=[LI() for i in range(n)]
u=lis[0][0]
vals=[[] for i in range(4)]
for i in range(n):
    if lis[i][0]==u:
        vals[0].append(lis[i][1])
    elif lis[i][0]==u+1:
        vals[1].append(lis[i][1])
    elif lis[i][0]==u+2:
        vals[2].append(lis[i][1])
    else:
        vals[3].append(lis[i][1])

for i in range(4):
    vals[i].sort(reverse=True)
    vals[i]=list(accumulate(vals[i]))
    vals[i]=[0]+vals[i]
mx=0

for i in range(len(vals[0])):
    for j in range(len(vals[1])):
        for k in range(len(vals[2])):
            for l in range(len(vals[3])):
                if u*i+(u+1)*j+(u+2)*k+(u+3)*l>w:
                    continue
                V=vals[0][i]+vals[1][j]+vals[2][k]+vals[3][l]
                if V>mx:
                    mx=V
print(mx)

Solution (Python):




import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial,sqrt
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,w=MI()
lis=[LI() for i in range(n)]
u=lis[0][0]
vals=[[] for i in range(4)]
for i in range(n):
    if lis[i][0]==u:
        vals[0].append(lis[i][1])
    elif lis[i][0]==u+1:
        vals[1].append(lis[i][1])
    elif lis[i][0]==u+2:
        vals[2].append(lis[i][1])
    else:
        vals[3].append(lis[i][1])

for i in range(4):
    vals[i].sort(reverse=True)
    vals[i]=list(accumulate(vals[i]))
    vals[i]=[0]+vals[i]
mx=0

for i in range(len(vals[0])):
    for j in range(len(vals[1])):
        for k in range(len(vals[2])):
            for l in range(len(vals[3])):
                if u*i+(u+1)*j+(u+2)*k+(u+3)*l>w:
                    continue
                V=vals[0][i]+vals[1][j]+vals[2][k]+vals[3][l]
                if V>mx:
                    mx=V
print(mx)

Solution (Python):
n,w = map(int,input().split())
wv = [list(map(int,input().split())) for _ in range(n)]

max1 = w // wv[0][0]
min1 = w // (wv[0][0] + 3)
seq = list(range(n))
ans = 0

w_min = wv[0][0]
w_list = [[] for _ in range(4)]

for wa,va in wv:
    w_list[wa-w_min].append(va)

for i in range(4):
    w_list[i].sort(reverse = True)

for i in range(4):
    for j in range(len(w_list[i])-1):
        w_list[i][j+1] += w_list[i][j]

for i in range(min1, max1+1):
    for w1 in range(i+1):
        for w2 in range(i-w1+1):
            for w3 in range(i-w1-w2+1):
                w4 = i - w1 - w2 - w3
                if w1 * w_min + w2 * (w_min+1) + w3 * (w_min+2) + w4 * (w_min+3) <= w:
                    if len(w_list[0]) >= w1 and len(w_list[1]) >= w2 and len(w_list[2]) >= w3 and len(w_list[3]) >= w4:
                        tmp = 0
                        if w1 >= 1:
                            tmp += w_list[0][w1-1]
                        if w2 >= 1:
                            tmp += w_list[1][w2-1]
                        if w3 >= 1:
                            tmp += w_list[2][w3-1]
                        if w4 >= 1:
                            tmp += w_list[3][w4-1]
                        ans = max(ans, tmp)

print(ans)

Solution (Python):
import sys
from collections import defaultdict

input = sys.stdin.readline


def main():
    N, W = [int(x) for x in input().split()]
    WV = [[int(x) for x in input().split()] for _ in range(N)]

    weight = set()
    weight.add(0)
    weight.add(WV[0][0])
    for i in range(1, N + 1):
        for j in range(3 * i):
            weight.add(WV[0][0] * i + j)

    weight = sorted(list(weight))

    dp = defaultdict(int)

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

    ans = 0
    for i in weight:
        if i > W:
            break
        ans = max(ans, dp[i])

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N)]
w0 = wv[0][0]
wv.sort(key=lambda x: (x[0], -x[1]))
w1, w2, w3, w4 = [], [], [], []
for w, v in wv:
    if w == w0:
        w1.append(v)
    elif w == w0 + 1:
        w2.append(v)
    elif w == w0 + 2:
        w3.append(v)
    else:
        w4.append(v)
Sw1, Sw2, Sw3, Sw4 = [0], [0], [0], [0]
S = 0
for v in w1:
    S += v
    Sw1.append(S)
S = 0
for v in w2:
    S += v
    Sw2.append(S)
S = 0
for v in w3:
    S += v
    Sw3.append(S)
S = 0
for v in w4:
    S += v
    Sw4.append(S)
l1, l2, l3, l4 = len(w1), len(w2), len(w3), len(w4)
V = 0
v = 0
for i in range(l1 + 1):
    if w0 * i > W:
        break
    for j in range(l2 + 1):
        if w0 * i + (w0 + 1) * j > W:
            break
        for k in range(l3 + 1):
            if w0 * i + (w0 + 1) * j + (w0 + 2) * k > W:
                break
            for l in range(l4 + 1):
                if w0 * i + (w0 + 1) * j + (w0 + 2) * k + (w0 + 3) * l > W:
                    break
                v = Sw1[i] + Sw2[j] + Sw3[k] + Sw4[l]
                V = max(V, v)
print(V)

Solution (Python):
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

INF = 10**18
eps = 10**-7

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

from collections import defaultdict

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

for (w,v) in goods:
    dnew = defaultdict(int)
    for key,value in d.items():
        dnew[key] = value
    for key,value in d.items():
        dnew[key+w] = max(dnew[key+w],d[key]+v)
    d = dnew
ans = 0
for k,v in d.items():
    if k <= W:
        ans = max(ans,v)
print(ans)

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7






N, great_W = getNM()
query = [getList() for i in range(N)]
wei = []
val = []
for i in range(N):
    w, v = query[i]
    wei.append(w)
    val.append(v)


wei_min = min(wei)
for i in range(N):
    wei[i] -= wei_min

def part_sum_5(n, k, limit, wei, val):
    dp = [[[0] * (limit + 1) for i in range(k + 1)] for i in range(n + 1)]

    
    for i in range(1, n + 1):
        for j in range(1, k + 1):
            for l in range(limit + 1):
                dp[i][j][l] = dp[i - 1][j][l]
                if l - wei[i - 1] >= 0:
                    dp[i][j][l] = max(dp[i - 1][j][l], dp[i - 1][j - 1][l - wei[i - 1]] + val[i - 1])

    res = 0
    for i in range(n + 1):
        for j in range(limit + 1):
            if i * wei_min <= (great_W - j):
                res = max(res, dp[N][i][j])

    return res

print(part_sum_5(N, N, 301, wei, val))

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7






N, W = getNM()
query = [getList() for i in range(N)]
wei = []
val = []
for i in range(N):
    w, v = query[i]
    wei.append(w)
    val.append(v)

wei_min = min(wei)
for i in range(N):
    wei[i] -= wei_min

def part_sum_5(n, k, limit, wei, val):
    dp = [[[0] * (limit + 1) for i in range(k + 1)] for i in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(1, k + 1):
            for l in range(limit + 1):
                dp[i][j][l] = dp[i - 1][j][l]
                if l - wei[i - 1] >= 0:
                    dp[i][j][l] = max(dp[i - 1][j][l], dp[i - 1][j - 1][l - wei[i - 1]] + val[i - 1])

    res = 0
    for i in range(n + 1):
        for j in range(limit + 1):
            if i * wei_min <= (W - j):
                res = max(res, dp[N][i][j])

    return res

print(part_sum_5(N, N, 301, wei, val))

Solution (Python):
from collections import defaultdict


def main():
    n, w = map(int, input().split())
    items = [list(map(int, input().split())) for _ in range(n)]
    DP = defaultdict(int)
    DP[0] = 0
    for weight, value in items:
        exists = list(DP.items())
        for key, total in exists:
            new_key = key + weight
            if new_key > w:
                continue
            new_total = total + value
            if DP[new_key] < new_total:
                DP[new_key] = new_total

    print(max(DP.values()))


if __name__ == "__main__":
    main()

Solution (Python):
from collections import defaultdict


def main():
    n, w = map(int, input().split())
    items = [list(map(int, input().split())) for _ in range(n)]
    DP = defaultdict(int)
    DP[0] = 0
    for weight, value in items:
        exists = list(DP.items())
        for key, total in exists:
            new_key = key + weight
            new_total = total + value
            if DP[new_key] < new_total:
                DP[new_key] = new_total

    candidates = [0]
    for weight, value in sorted(DP.items()):
        if weight > w:
            break
        candidates.append(value)

    print(max(candidates))


if __name__ == "__main__":
    main()

Solution (Python):
n,W=map(int,input().split())
w=[0 for i in range(n)]
v=[[] for i in range(4)]
dp=[[0] for i in range(4)]
for i in range(n):
  w[i],vi=map(int,input().split())
  v[w[i]-w[0]].append(vi)
for i in range(4):
  v[i].sort(reverse=True)
  for j in v[i]:
    dp[i].append(dp[i][-1]+j)
def dfs(i,cost):
  if cost>W:
    return -10**10
  elif i==4:
    return 0
  else:
    val=0
    for j in range(len(dp[i])):
      val=max(val,dp[i][j]+dfs(i+1,cost+j*(w[0]+i)))
    return val
print(dfs(0,0))

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





N,W = IL()
dic = DD(list)

w0,v = IL()
heapq.heappush(dic[w0],-v)
for _ in range(N-1):
  w,v = IL()
  heapq.heappush(dic[w],-v)

DIC = DD(list)
for i in range(4):
  DIC[w0+i] = [0]
  while dic[w0+i]:
    DIC[w0+i].append(DIC[w0+i][-1]-heapq.heappop(dic[w0+i]))

MAX = 0
for i in range(len(DIC[w0])):
  for j in range(len(DIC[w0+1])):
    for k in range(len(DIC[w0+2])):
      for l in range(len(DIC[w0+3])):
        if i*w0+j*(w0+1)+k*(w0+2)+l*(w0+3) <= W:
          MAX = max(MAX,DIC[w0][i]+DIC[w0+1][j]+DIC[w0+2][k]+DIC[w0+3][l])
print(MAX)

Solution (Python):
n,w = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
b = [[] for _ in range(4)]
for i,j in a:
    b[i-a[0][0]].append(j)
for i in range(4):
    b[i].sort()
    b[i].reverse()
for i in range(4):
    for j in range(1,len(b[i])):
        b[i][j] += b[i][j-1]
    b[i].reverse()
    b[i].append(0)
    b[i].reverse()

ans = 0
for i in range(len(b[0])):
    for j in range(len(b[1])):
        for k in range(len(b[2])):
            for l in range(len(b[3])):
                
                if a[0][0]*i+(a[0][0]+1)*j+(a[0][0]+2)*k+(a[0][0]+3)*l <= w:
                    
                    ans = max(ans, b[0][i]+b[1][j]+b[2][k]+b[3][l])
print(ans)

Solution (Python):
def resolve():
    N, W = list(map(int, input().split()))
    WV = [list(map(int, input().split())) for _ in range(N)]
    wbase = WV[0][0]
    d = {
        wbase: [0],
        wbase+1: [0],
        wbase+2: [0],
        wbase+3: [0],
    }
    for w, v in WV:
        d[w].append(v)
    for v in d.values():
        v.sort(reverse=True)
    
    accs = {}
    for i in range(4):
        accs[wbase+i] = [0]
        for j in range(len(d[wbase+i])):
            accs[wbase+i].append(accs[wbase+i][j]+d[wbase+i][j])
    
    res = 0
    for i in range(len(d[wbase])):
        for j in range(len(d[wbase+1])):
            for k in range(len(d[wbase+2])):
                for l in range(len(d[wbase+3])):
                    if i*wbase+j*(wbase+1)+k*(wbase+2)+l*(wbase+3) <= W:
                        res = max(res, accs[wbase][i]+accs[wbase+1][j]+accs[wbase+2][k]+accs[wbase+3][l])
    print(res)


if __name__ == '__main__':
    resolve()

Solution (Python):
N, W = map(int, input().split())
I = [tuple(map(int, input().split())) for _ in range(N)]
w0 = I[0][0]

dp = [[[0 for k in range(N * 3 + 1)] for j in range(N + 1)] for i in range(N + 1)]

for i in range(N):
    w, v = I[i]
    for j in range(N):
        for k in range(3 * N + 1):
            if k - (w - w0) >= 0:
                dp[i + 1][j + 1][k] = max(dp[i][j + 1][k], dp[i][j][k - (w - w0)] + v)
            else:
                dp[i + 1][j + 1][k] = dp[i][j + 1][k]

res = 0

for i in range(N + 1):
    for j in range(N + 1):
        for k in range(3 * N + 1):
            if w0 * j + k <= W:
                res = max(res, dp[i][j][k])

print(res)