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.



Sample input:
4 6
2 1
3 4
4 10
3 4


Sample output:
11

Submission status: Wrong Answer

Solution code:
import numpy as np

def generate():
    newGen = np.zeros(n)
    for p in range(pop):
        gen = np.random.rand(n)
        for i in range(n):
            if gen[i] > 0.5:
                gen[i] = 1
            else:
                gen[i] = 0
        newGen = np.vstack([newGen,gen])
    newGen = np.vsplit(newGen,[1])[1]
    return newGen

def evaluate(gen):
    sum = np.zeros(pop)
    for p in range(pop):
        for i in range(n):
            sum[p] += v[i][1] * gen[p][i]
    sum = sum.reshape(pop, 1)
    gen = np.hstack([gen, sum])
    return gen

def best(gen):
    best0 = gen[0]
    for p in range(1,pop):
        if best0[-1] < gen[p][-1]:
            best0 = gen[p]
    return best0

def select(b,p):
    parents = np.zeros(b.shape[1])
    for i in range(p):
        p1 = b[np.random.randint(0, b.shape[0] - 1)]
        p2 = b[np.random.randint(0, b.shape[0] - 1)]
        if p1[-1] < p2[-1]:
            parents = np.vstack([parents, p2])
        else:
            parents = np.vstack([parents, p1])
    return np.vsplit(parents,[1])[1]

def crossover(parents):
    parents = np.hsplit(parents, [-1])[0]
    newGen = np.zeros(parents.shape[1])
    for i in range(parents.shape[0] / 2):
        l = np.random.randint(1, parents.shape[1] - 1)
        p1_0, p1_1 = np.hsplit(parents[i * 2], [l])
        p2_0, p2_1 = np.hsplit(parents[i * 2 + 1], [l])
        c1 = np.hstack([p1_0, p2_1])
        c2 = np.hstack([p1_1, p2_0])
        newGen = np.vstack([newGen, c1])
        newGen = np.vstack([newGen, c2])
    return np.vsplit(newGen, [1])[1]

def mutation(newGen):
    for p in range(pop):
        w_sum = 0
        for i in range(n):
            w_sum += newGen[p][i] * v[i][0]
        if w_sum > w:
            ran = np.random.permutation(np.arange(n))
            while(w_sum > w):
                ran, q = np.hsplit(ran,[-1])
                if newGen[p][q] == 1:
                    w_sum -= newGen[p][q] * v[q][0]
                    newGen[p][q] = 0
    return newGen


pop = 10
n, w = map(int,raw_input().split())
v = []
N = 100
for i in range(n):
    v.append(map(int,raw_input().split()))

eval = evaluate(generate())
c = mutation(crossover(select(eval,pop)))
eval = evaluate(c)
be = best(eval)
for i in range(N):
    c = mutation(crossover(select(eval,pop)))
    eval = evaluate(c)
    if be[-1] < best(eval)[-1]:
        be = best(eval)
print int(be[-1])

Submission status: Wrong Answer

Solution code:
import numpy as np

def generate():
    newGen = np.zeros(n)
    for p in range(pop):
        gen = np.random.rand(n)
        for i in range(n):
            if gen[i] > 0.5:
                gen[i] = 1
            else:
                gen[i] = 0
        newGen = np.vstack([newGen,gen])
    newGen = np.vsplit(newGen,[1])[1]
    return newGen

def evaluate(gen):
    sum = np.zeros(pop)
    for p in range(pop):
        for i in range(n):
            sum[p] += v[i][1] * gen[p][i]
    sum = sum.reshape(pop, 1)
    gen = np.hstack([gen, sum])
    return gen

def best(gen):
    best0 = gen[0]
    for p in range(1,pop):
        if best0[-1] < gen[p][-1]:
            best0 = gen[p]
    return best0

def select(b,p):
    parents = np.zeros(b.shape[1])
    for i in range(p):
        p1 = b[np.random.randint(0, b.shape[0] - 1)]
        p2 = b[np.random.randint(0, b.shape[0] - 1)]
        if p1[-1] < p2[-1]:
            parents = np.vstack([parents, p2])
        else:
            parents = np.vstack([parents, p1])
    return np.vsplit(parents,[1])[1]

def crossover(parents):
    parents = np.hsplit(parents, [-1])[0]
    newGen = np.zeros(parents.shape[1])
    for i in range(parents.shape[0] / 2):
        l = np.random.randint(1, parents.shape[1] - 1)
        p1_0, p1_1 = np.hsplit(parents[i * 2], [l])
        p2_0, p2_1 = np.hsplit(parents[i * 2 + 1], [l])
        c1 = np.hstack([p1_0, p2_1])
        c2 = np.hstack([p1_1, p2_0])
        newGen = np.vstack([newGen, c1])
        newGen = np.vstack([newGen, c2])
    return np.vsplit(newGen, [1])[1]

def mutation(newGen):
    for p in range(pop):
        w_sum = 0
        for i in range(n):
            w_sum += newGen[p][i] * v[i][0]
        if w_sum > w:
            ran = np.random.permutation(np.arange(n))
            while(w_sum > w):
                ran, q = np.hsplit(ran,[-1])
                if newGen[p][q] == 1:
                    w_sum -= newGen[p][q] * v[q][0]
                    newGen[p][q] = 0
    return newGen


pop = 10
n, w = map(int,raw_input().split())
v = []
N = 100
for i in range(n):
    v.append(map(int,raw_input().split()))

eval = evaluate(generate())
c = mutation(crossover(select(eval,pop)))
eval = evaluate(c)
be = best(eval)
for i in range(N):
    c = mutation(crossover(select(eval,pop)))
    eval = evaluate(c)
    if be[-1] < best(eval)[-1]:
        be = best(eval)
print be[-1]

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys

class BagItem(object):
    def __init__(self, w, v):
        super(BagItem, self).__init__()
        self.w = w
        self.v = v

    def get_value(self):
        return self.v

    def get_weight(self):
        return self.w

    def get_sort_value(self):
        return self.v * 10 ** 10 - self.w



n,w = [int(x) for x in input().rstrip().split(" ")]
items = []

for i in range(n):
    nn, ww = [int(x) for x in input().rstrip().split(" ")]
    items.append(BagItem(nn, ww))

items.sort(key=BagItem.get_sort_value, reverse=True)

total_value = 0
total_weight = 0
for i in range(len(items)):
    if total_weight + items[i].get_weight() > w:
        continue
    total_value = total_value + items[i].get_value()
    total_weight = total_weight + items[i].get_weight()

print(total_value)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys

class BagItem(object):
    def __init__(self, w, v):
        super(BagItem, self).__init__()
        self.w = w
        self.v = v

    def get_value(self):
        return self.v

    def get_weight(self):
        return self.w



n,w = [int(x) for x in input().rstrip().split(" ")]
items = []

for i in range(n):
    nn, ww = [int(x) for x in input().rstrip().split(" ")]
    items.append(BagItem(nn, ww))

items.sort(key=BagItem.get_value, reverse=True)

total_value = 0
total_weight = 0
for i in range(len(items)):
    if total_weight + items[i].get_weight() > w:
        continue
    total_value = total_value + items[i].get_value()
    total_weight = total_weight + items[i].get_weight()

print(total_value)

Submission status: Wrong Answer

Solution code:
n, w = map(int, input().split())
shop = []
for i in range(n):
    shop.append( list(map(int, input().split())) )
s = sorted(shop, key= lambda item: item[1]/item[0], reverse=True)
bag = [0, 0]
i = 0
while i < n:
    item = s[i]
    i += 1
    if bag[0]+item[0] <= w:
        bag[0] += item[0]
        bag[1] += item[1]
    else:
        continue
print(bag[1])

Submission status: Wrong Answer

Solution code:
A = list(map(int,input().split(" ")))
B = list()
W = list(map(int,"0 0 0 0".split(" ")))
V = list(map(int,"0 0 0 0".split(" ")))

for i in range(A[0]):
    B.append(list(map(int,input().split(" "))))
    B[i].append(B[i][1]/B[i][0])

C = sorted(B, key=lambda x: x[2],reverse=True)

for ii in range(4):
    for i in range(A[0]):
        if C[i][0] <= ii + B[1][0]:
            if A[1] >= W[ii] + C[i][0]:
                W[ii] = W[ii] + C[i][0]
                V[ii] = V[ii] + C[i][1]
                if A[1] == W[ii]:
                    break

print(max(V))

Submission status: Wrong Answer

Solution code:
def main():
    n, w = map(int, input().split())
    shop = []
    for i in range(n):
        shop.append( list(map(int, input().split())) )
    s = sorted(shop, key= lambda item: item[1]/item[0], reverse=True)
    # print(n, w, s)
    bag = [0, 0]
    i = 0
    while i < n:
        item = s[i]
        i += 1
        if bag[0]+item[0] <= w:
            bag[0] += item[0]
            bag[1] += item[1]
        else:
            continue
    print(bag[1])
main()

Submission status: Wrong Answer

Solution code:
A = list(map(int,input().split(" ")))
B = list()
W = list(map(int,"0 0 0 0".split(" ")))
V = list(map(int,"0 0 0 0".split(" ")))
WMIN = 10000000000

for i in range(A[0]):
    B.append(list(map(int,input().split(" "))))
    B[i].append(B[i][1]/B[i][0])
    WMIN = min(WMIN,B[i][0])

C = sorted(B, key=lambda x: x[2],reverse=True)

for ii in range(4):
    for i in range(A[0]):
        if C[i][0] <= ii + WMIN:
            if A[1] >= W[ii] + C[i][0]:
                W[ii] = W[ii] + C[i][0]
                V[ii] = V[ii] + C[i][1]
                if A[1] == W[ii]:
                    break

print(max(V))

Submission status: Wrong Answer

Solution code:
n,w=map(int,input().split())
sk=[-1 for i in range(w+1)]
sk[0]=0
tmp=sk[:]
for i in range(n):
    c,v=map(int,input().split())
    tmp=sk[:]
    for j in range(w+1):
        if tmp[j]!=-1:
            if j+c<len(sk) and sk[j+c]<sk[j]+v:
                sk[j+c]=sk[j]+v
print(max(sk))

Submission status: Wrong Answer

Solution code:
A = list(map(int,input().split(" ")))
B = list()
W = 0
V = 0

for i in range(A[0]):
    B.append(list(map(int,input().split(" "))))
    B[i].append(B[i][1]/B[i][0])

C = sorted(B, key=lambda x: x[2],reverse=True)

for i in range(A[0]):
    if A[1] >= W + C[i][0]:
        W = W + C[i][0]
        V = V + C[i][1]
        if A[1] == W:
            break

print(V)

Submission status: Time Limit Exceeded

Solution code:
N, W = map(int, input().split())
w, v = [], []
for _ in range(N):
    x, y = map(int, input().split())
    w.append(x)
    v.append(y)
from collections import defaultdict
dp = defaultdict(lambda: 0)
dp[0,0] = 0

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

Submission status: Time Limit Exceeded

Solution code:
n, w = map(int, input().split())
items = [list(map(int, input().split())) for _ in range(n)]
if w < items[0][0] :
    print(0)
    exit()
w_sum = 0
v_sum = 0
for i in range(n):
    w_sum += items[i][0]
    v_sum += items[i][1]
if w >= w_sum:
    print(v_sum)
    exit()
dp = {}
#for j in range(1,w+1):
for j in range(items[0][0],w+1):
    for i in range(1,n+1):
        if j-items[i-1][0] >= 0:
            if str(i-1)+":"+str(j) not in dp:
                dp[str(i - 1) + ":" + str(j)] = 0
            if str(i-1)+":"+str(j-items[i-1][0]) not in dp:
                dp[str(i - 1) + ":" + str(j - items[i - 1][0])] = 0
            dp[str(i)+":"+str(j)] = max(dp[str(i-1)+":"+str(j)],dp[str(i-1)+":"+str(j-items[i-1][0])]+items[i-1][1])
        else:
            if str(i-1)+":"+str(j) not in dp:
                dp[str(i - 1) + ":" + str(j)] = 0
            dp[str(i)+":"+str(j)] = dp[str(i-1)+":"+str(j)]
print(dp[str(n)+":"+str(w)])

Submission status: Time Limit Exceeded

Solution code:
n, w = map(int, input().split())
items = [list(map(int, input().split())) for _ in range(n)]
dp = {}
for j in range(1,w+1):
    for i in range(1,n+1):
        if j-items[i-1][0] >= 0:
            if str(i-1)+":"+str(j) not in dp:
                dp[str(i - 1) + ":" + str(j)] = 0
            if str(i-1)+":"+str(j-items[i-1][0]) not in dp:
                dp[str(i - 1) + ":" + str(j - items[i - 1][0])] = 0
            dp[str(i)+":"+str(j)] = max(dp[str(i-1)+":"+str(j)],dp[str(i-1)+":"+str(j-items[i-1][0])]+items[i-1][1])
        else:
            if str(i-1)+":"+str(j) not in dp:
                dp[str(i - 1) + ":" + str(j)] = 0
            dp[str(i)+":"+str(j)] = dp[str(i-1)+":"+str(j)]
print(dp[str(n)+":"+str(w)])

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

def main():
    n,w=map(int,stdin.readline().strip().split())
    t=[list(map(int,stdin.readline().strip().split())) for _ in range(n)]
    w1=t[0][0]
    for i in range(4):
        t.append([w1+i,0])
    arr=[sorted([x for x in t if x[0]==w1+i],reverse=True,key=lambda e:e[1]) for i in range(4)]
    # arr=[x.sort(reverse=True,key=lambda e:e[1]) for x in arr]
    arrlen=list(map(len,arr))
    ans=0
    sw=0
    sv=0
    for i0 in range(arrlen[0]):
         for i1 in range(arrlen[1]):
              for i2 in range(arrlen[2]):
                   for i3 in range(arrlen[3]):
                        sw=sum([x[0] for x in arr[0][:i0]])+sum([x[0] for x in arr[1][:i1]])\
                          +sum([x[0] for x in arr[2][:i2]])+sum([x[0] for x in arr[3][:i3]])
                        sv=sum([x[1] for x in arr[0][:i0]])+sum([x[1] for x in arr[1][:i1]])\
                          +sum([x[1] for x in arr[2][:i2]])+sum([x[1] for x in arr[3][:i3]])
                        if sw<=w:
                            ans=max(ans,sv)
    print(ans)
    # wts=list(map(lambda l:l[0]-w1-1, t))
    # val=list(map(lambda l:l[1], t))

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
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])))
    
    max_len = max(list(map(lambda x:len(x),acc)))
    comb = list(product(list(range(max_len+1)),repeat=4))
    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()

Submission status: Time Limit Exceeded

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


if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
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 j in range(N + 1):
    for k in range(3 * N + 1):
        if w0 * j + k <= W:
            res = max(res, dp[N][j][k])

print(res)

Submission status: Time Limit Exceeded

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())
x = w[0]
for i in range(n): w[i] -= x
dp = [[[0]*(4*n+1) for _ in range(n+1)] for _ in range(n+1)]

for i in range(n):
    for j in range(i+1):
        for k in range(4*n+1):
            if (j+1)*x+k <= W and k-w[i] >= 0:
                dp[i+1][j+1][k] = max(dp[i+1][j+1][k],dp[i][j][k-w[i]]+v[i])
            dp[i+1][j][k] = max(dp[i+1][j][k],dp[i][j][k])

"""
for i in range(n+1):
    print(i,"///////////////////////////////////////////////")
    for j in range(n+1):
        print(dp[i][j])
"""
print(max(max(dp[n][j]) for j in range(n+1)))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
n,w= map(int,input().split())
wlist=[]
vlist=[]
for i in range(n):
    w1,v1= map(int,input().split())
    wlist.append(w1)
    vlist.append(v1)
dp = [[dict() for _ in range(n+1)] for _ in range(n+1)]
for i in range(n+1):
    dp[0][i][0]=0
    dp[i][0][0]=0
gmax=0
for i in range(1,n+1):
    for j in range(1,n+1):
        for ulkey in dp[i-1][j-1].keys():
            tempdpij=0
            if (ulkey+wlist[i-1])>w:pass
            else:
                if (ulkey+wlist[i-1]) in dp[i-1][j].keys():
                    tempul = dp[i-1][j-1][ulkey] + vlist[i-1]
                    tempu = dp[i-1][j][ulkey+wlist[i-1]]
                    tempdpij = max(tempul,tempu)
                else:
                    tempdpij = dp[i-1][j-1][ulkey] + vlist[i-1]
                dp[i][j][ulkey+wlist[i-1]] = tempdpij
                gmax = max(gmax,tempdpij)
        for ukey in dp[i-1][j].keys():
            if not (ukey-wlist[i-1]) in dp[i-1][j-1].keys():
                dp[i][j][ukey]=dp[i-1][j][ukey]
print(gmax)

Submission status: Time Limit Exceeded

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

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

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

Submission status: Time Limit Exceeded

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

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)
 
# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
 
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
 
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
 
        if x == y:
            return
 
        if self.parents[x] > self.parents[y]:
            x, y = y, x
 
        self.parents[x] += self.parents[y]
        self.parents[y] = x
 
    def size(self, x):
        return -self.parents[self.find(x)]
 
    def same(self, x, y):
        return self.find(x) == self.find(y)
 
    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
 
    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]
 
    def group_count(self):
        return len(self.roots())
 
    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}
 
    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
 
def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True
 
 
# ワーシャルフロイド (任意の2頂点の対に対して最短経路を求める)
# 計算量n^3 (nは頂点の数)
def warshall_floyd(d, n):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d
 
 
# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d
 
# 素因数分解
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
 
# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)
 
# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)
 
# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)
 
# 素数判定
 
 
 
# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []
 
    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P
 
# 同じものを含む順列
def permutation_with_duplicates(L):
 
    if L == []:
        return [[]]
 
    else:
        ret = []
 
        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))
 
        for i in S:
 
            data = L[:]
            data.remove(i)
 
            for j in permutation_with_duplicates(data):
                ret.append([i] + j)
 
        return ret
 
 
# ここから書き始める
N, W = map(int, input().split())
w = [0 for i in range(N)]
v = [0 for i in range(N)]
for i in range(N):
    w[i], v[i] = map(int, input().split())
dp = [[0 for j in range(W + 1)] for i in range(N)]
for i in range(N):
    for j in range(W + 1):
        if i == 0:
            if j == w[i]:
                dp[i][j] = v[i]
            else:
                dp[i][j] = 0
        else:
            dp[i][j] = dp[i - 1][j]
            if 0 <= j - w[i]:
                dp[i][j] = max(dp[i][j], dp[i - 1][j - w[i]] + v[i])
ans = max(dp[-1])
# print(dp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True


# ワーシャルフロイド (任意の2頂点の対に対して最短経路を求める)
# 計算量n^3 (nは頂点の数)
def warshall_floyd(d, n):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d


# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
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

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定



# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
N, W = map(int, input().split())
w = [0 for i in range(N)]
v = [0 for i in range(N)]
for i in range(N):
    w[i], v[i] = map(int, input().split())
dp = [[0 for j in range(W + 1)] for i in range(N)]
for i in range(N):
    for j in range(W + 1):
        if i == 0:
            if j == w[i]:
                dp[i][j] = v[i]
            else:
                dp[i][j] = 0
        else:
            dp[i][j] = dp[i - 1][j]
            if 0 <= j - w[i]:
                dp[i][j] = max(dp[i][j], dp[i - 1][j - w[i]] + v[i])
ans = max(dp[-1])
# print(dp)
print(ans)

Submission status: Time Limit Exceeded

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

ab = [list(map(int, input().split())) for _ in range(n)]
dp=[[ 0 for i in range(w+1)] for j in range(n+1)]

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

Submission status: Time Limit Exceeded

Solution code:
n,w = map(int,input().split())
l =[list(map(int,input().split())) for i in range(n)]

dp = [[[0]*(3*n+1) for i in range(n+1)] for j in range(n+1)]
s = l[0][0]

for i in range(n):
    dt = l[i][0]-s
    for j in range(n):
        for k in range(3*n+1):
            if k -dt >= 0:
                dp[i+1][j+1][k] = max(dp[i][j+1][k],dp[i][j][k-dt]+l[i][1])
            else:
                dp[i+1][j+1][k] = dp[i][j+1][k]

ans = 0
for i in range(1,n+1):
    for j in range(3*n+1):
        if i*s+j <= w:
            ans = max(ans,dp[-1][i][j])
print(ans)

Submission status: Time Limit Exceeded

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

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

w1,v1 = map(int,input().split())
for i in range(3*n+1):
    dp[0][0][i] = v1

for i in range(1,n):
    w,v = map(int,input().split())
    w -= w1
    for j in range(n):
        for k in range(3*n+1):
            if j>0 and k>=w:
                dp[i][j][k] = max(dp[i-1][j][k], dp[i-1][j-1][k-w] + v)
            elif k>=w:
                dp[i][0][k] = max(dp[i-1][0][k], v)
            else:
                dp[i][j][k] = dp[i-1][j][k]

ans = 0
for i in range(n):
    for j in range(3*n+1):
        if w1*(i+1) + j>W: continue
        ans = max(ans,dp[-1][i][j])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,W=map(int,input().split())
a=[list(map(int,input().split())) for i in range(N)]
a.sort(key=lambda x: x[1])
dp=[[0 for i in range(W+1)]for k in range(N+1)]

def aaa(N,W,a):
    for i in range(N):
        for k in range(W+1):
            if k-a[i][0]>=0:
                dp[i+1][k]=max(dp[i][k],dp[i][k-a[i][0]]+a[i][1])
            else:
                dp[i+1][k]=dp[i][k]
    return dp[N][W]
ans=aaa(N,W,a)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,W=map(int,input().split())
a=[list(map(int,input().split())) for i in range(N)]
dp=[[0 for i in range(W+1)]for k in range(N+1)]

def aaa(N,W,a):
    for i in range(N):
        for k in range(W+1):
            if k-a[i][0]>=0:
                dp[i+1][k]=max(dp[i][k],dp[i][k-a[i][0]]+a[i][1])
            else:
                dp[i+1][k]=dp[i][k]
    return dp[N][W]
ans=aaa(N,W,a)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,W=map(int,input().split())
a=[list(map(int,input().split())) for i in range(N)]
dp=[[0 for i in range(W+1)]for k in range(N+1)]

for i in range(N):
    for k in range(W):
        if k+1-a[i][0]>=0:
            dp[i+1][k+1]=max(dp[i][k+1],dp[i][k+1-a[i][0]]+a[i][1])
        else:
            dp[i+1][k+1]=dp[i][k+1]
ans=dp[N][W]
print(ans)