[PYTHON] Atcoder ABC60 D --Simple Knapsack Separate Solution

The characteristic is that the width of w is small I was scared for the first time because it is a constraint that I do not see easily

Dynamic programming

Because it ’s a knapsack, right? Then you have to do dp.

I tried it It's hard if w remains 10 ^ 9, so let's subtract base = w1 Then the size of dp is about 101 x 301, so it will be in time at all

dp.py


N,W=map(int,input().split())
dp=[[-1]*301 for i in range(N+1)]
dp[0][0]=0

for i in range(N):
    w,v=map(int,input().split())
    if i==0:
        base=w
    for i in range(N)[::-1]:
        for j in range(301)[::-1]:
            if dp[i][j]!=-1:
                dp[i+1][j+w-base]=max(dp[i][j]+v,dp[i+1][j+w-base])

ans=0
for index,item in enumerate(dp):
    if W-index*base+1<=0:
        break
    ans=max(max(item[:W-index*base+1]),ans)

print(ans)

greedy

Since there are only 4 types of weight, you can take out the one with large v from the list that summarizes each w. The number to be taken out should be brute force for each w

greedy.py


def saiki(value,HP,num):
    if num==0:
        value+=wa[0][min(HP//base,len(wa[0])-1)]
        ans.append(value)
    else:
        for i in range(len(wa[num])):
            if HP-(num+base)*i>=0:
                saiki(value+wa[num][i],HP-(num+base)*i,num-1)
            else:
                break
    return


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

lis=[[] for i in range(4)]

for i in range(N):
    w,v=map(int,input().split())
    if i==0:
        base=w
    lis[w-base].append(v)

lis=list(map(lambda x:sorted(x, reverse=True),lis))

wa=[[0] for i in range(4)]

for i in range(len(wa)):
    for item in lis[i]:
        wa[i].append(wa[i][-1]+item)

ans=[]
saiki(0,W,3)
    

print(max(ans))

Why are ans arranged in an array? I'm not good at bugs like "not yet defined" when dealing with numbers

Recommended Posts

Atcoder ABC60 D --Simple Knapsack Separate Solution
Atcoder ABC099 C --Strange Bank Separate Solution
AtCoder ABC 182 Python (A ~ D)
AtCoder ABC176
AtCoder ABC177
AtCoder ABC155 Problem D Pairs Review Note 1
Solve AtCoder ABC168 with python (A ~ D)
AtCoder ABC 174 Python
AtCoder ABC187 Python
AtCoder ABC188 Python
AtCoder ABC 175 Python
Atcoder ABC115 Past Exercises
AtCoder ABC155 Problem D Pairs Review Note 2 NumPy and Python
Solving with Ruby and Python AtCoder ABC178 D Dynamic programming
Solving with Ruby and Python AtCoder ABC151 D Breadth-first search
Solve with Ruby and Python AtCoder ABC133 D Cumulative sum
AtCoder ABC151 Problem D Speed comparison in C ++ / Python / PyPy
AtCoder ABC156 Problem D Bouquet mod calculation and permutations, etc.
Solving with Ruby and Python AtCoder ABC138 D Adjacency list