01 backpacks full backpack, multiple backpack, mixed bag, backpack-D expenses, grouping backpack, knapsack problem several programs seeking

101 knapsack problem

Have N N And a capacity of items V V Backpack. Each item can only be usedonce

The first i i Volume of items is v i v_i The value is w i w_i . Which solving the items into the backpack, these items make the total volumeDoes not exceedBackpack capacity, and the total value of the maximum.

Resolution:

Status means:

  • f[i][j] Look expressed agoi An article, the total volume ofj The maximum value under the circumstances.

State transition:

  1. Do not choose the firsti Two items,f[i][j] = f[i-1]f[j] , Constant volume, equal to a state of the article.

  2. Is selected from the i-th item,f[i][j] = f[i-1][j-v[i]] + v[i], Smaller size, plus the value of the current article.

  • Therefore, the transfer equationf[i][j] = max(1, 2)

boundary:

  • f[0][j], f[i][0] = 0 Case, the volume of the article or to the maximum value of 0 is 0
def func(v, w, m): # V is the volume, w is the value, m is the total volume
    f = [[0]*(m+1) for _ in range(n+1)]  # F [i] [j] denotes the i-th former article, the total volume in the case where the maximum value of j
    for i in range(1, len(w) + 1):  Starting with the first item #
        for j in range(1, m + 1):  Volume # 1 starts from
            f[i][j] = f[i - 1][j]  # Uncheck this article
            if j >= v[i - 1]:  # If you can hold this item
                f[i][j] = max(f[i][j], f[i-1][j-v[i-1]] + w[i-1])  # Choose this article
    print(f[n][m])
    # print(max([max(x) for x in f]))
  • time complexity O(n*V)
  • Space complexityO(n*V)

Storage optimization

All states can be usedOne-dimensional arraySaid the reduced space complexityO(V)

The key point is that it must be used in the current state of the layer state. I.e., this layer has not been modified to a state.

Because one of the current state of and the state relevant, can be optimized as a one-dimensional array. First look at the two state transition:

  1. f[i][j] = f[i-1][j]
  2. f[i][j] = f[i-1][j-v[i]] + w[i]

The first state: we can directly usef[j] instead. Because traversedf[j] Time,f[j] It has not changed, it's still a layer state. So, we did not have to judge when to choose, when not selected. It can be unified.

The second states: a state when traversedf[j]When, becausej-v[j] < j, The statef[j-v[j]]It has traversed, and this layer is the state we want is a layer off[j-v[j]]. Therefore, the volume can descending traverse, so the traversalf[j]Time,f[j-v[j]]Yet traversed, the state is still on the floor.

def func(v, w, m): # M total weight
    f = [0]*(m+1)
    for i in range(1, len(w)+1):  # Item [1, n]
        for j in range(m, v[i-1]-1, -1):  # Volume [m, v [i]]
            f[j] = max(f[j], f[j - v[i-1]] + w[i-1])
    print(f[m])

About optimized representation of the results

For the final result can be directly output f [V], rather than traverse the entire array takes a maximum value, because when wef [V] are all initialized to zeroTime, f [V] indicates the maximum value that can be obtained when the volume is less than equal to V.

When we only f [0] is initialized to 0, the rest of thef [i] Initialization -INFYou can findThe maximum value is obtained when exactly the volume V. This ensures that f [V] is transferred from the f [0] over, transferred from other states to come is negative infinity.

Intuitive understanding, when we ask for is to get the greatest value when the volume is V exactly. Consider the situation, we traverse from one volume to traversing V, may be some of the volume of the article and fit any case they should state does not exist and should not be transferred to a later state. So we should be initialized to -INF, this state is transferred to the rear -INF.

2 full knapsack problem

Have N N Kinds of goods and a capacity V V Backpack, each item hasUnlimited pieces available. The volume of the i-th item is vi, the value is wi.

Which solving the items into the backpack, these items make the total volumeDoes not exceedBackpack capacity, and the total value of the maximum. The maximum output value.

Resolution:

Status means:

  • We use the optimizationOne-dimensional arrayTo represent the state,f [i] indicates the maximum volume value can be obtained in the case of i.
  • res = max(f[0 ... m]), M is the total volume.

Extended 01 knapsack problem,v is the volume, w is the value, m is the total volume

def func(v, w, m):
    n = len(w) - 1
    f = [0]*(m+1)
    for i in range(1, n + 1):  # Item [1, n]
        for j in range(m, v[i-1]-1, -1): # Volume [m, 1]
            for k in range(1, j//v[i-1] + 1): Number # [1, j // v [i]]
                f[j] = max(f[j], f[j - k*v[i-1]] + k*w[i-1])
    print(f[m])

optimization,Just 01 backpack in the second cycle can be reversed!

def func(v, w, m):
    f = [0]*(m+1)
    for i in range(1,len(w) + 1):  # Item [1, n]
        for j in range(v[i-1], m+1): # Volume [v [i], m]
            f[j] = max(f[j], f[j - v[i-1]] + w[i-1])
    print(f[m])

We think about why we had to reverse the cycle?

becausef[i][j]Byf[i-1][j-v]Derived, we just reverse cycle ensures that each item only been used once, but if we are cycling sequence, indicating ourf[i][j]Byf[i][j-v]Derived, each item can be use many times. But that is exactly what we want in full backpack.

3 multiple knapsack problem

There are N kinds of goods and a backpack capacity of V. Up to the i-th item si pieces, each volume is VI, a value wi.

Which solving the items into the backpack, can not exceed the total volume of the article capacity of the backpack, and the sum of the maximum value. The maximum output value.

Resolution:

Status means:

  • f [i] indicates the maximum volume value can be obtained in the case of i.

State transition:

01 is an extension of the backpack, 01 knapsack problem is selected each item only and not vote for the two cases. Multiple knapsack problem is you can not vote, you can choose one, two, until s i s_i More

  • f[j] = max(f[j], f[j-v[i]]+w[i], f[j-2*v[i]]+2*w[i])

01 knapsack problem extension

def func(v, w, m):
    f = [0]*(m+1)
    for i in range(1, len(w) + 1):  # Item [1, n]
        for j in range(m, v[i-1]-1, -1): # Volume [m, v [i-1]]
            for k in range(1, s[i-1] + 1): # Number [1, s [i]]
                if k*v[i-1] <= j:   # Ensure that the lower back of the package
                    f[j] = max(f[j], f[j - k*v[i-1]] + k*w[i-1])
    print(f[m])

Time complexity of O (n ^ 3)

Optimization Method One: Binary Optimization

  • 01 knapsack problem into binary optimization.

Given any number s, a minimum number can be divided into a number s, the number of each selected or not selected, so that these may be combined into a less number s all.

With rat poison and a test token, s can be divided into a number of bits (rounding the log (s + 1)). Selected or not selected are representative of whether the corresponding bit is a 1 on.

7 = 1 = 001 111 is split, 2 = 010, 4 = 100, representing each of the binary 1

0 = not selected, is selected from = 1, 2 = 1 and selected from the group selected from 2,3 = 2,4 = 4,5 = selected from selected from 1 and 2 and is selected from 4,6 = 4,7 = 4 is selected from 1 and 2 and .

** If the last remaining portion of the split value added directly backpack. After ** For example, 13 = 1101, then divided into 0001, 0010, 0100, 0110. The first three digits may be combined in any number less than 7, each number plus 0110 (= 6) can be combined into a larger than any 6 is equal to the number of 13 or less, it still can be composed of an arbitrary number of 13 or less.

from collections import namedtuple

def func_1(v, w, s, m):  Volume # v, w values, s number, m the total volume
    Good = namedtuple('Good', ['v', 'w'])
    goods = [] # Store all items
    f = [0] * (m + 1)
    # Multiple number of binary objects split
    for i in range(len(w)):
        k = 1
        while k <= s[i]:
            s[i] -= k
            goods.append(Good(v[i]*k, w[i]*k))
            k *= 2
        if s[i] > 0: goods.append(Good(v[i]*s[i], w[i]*s[i]))

    At this time, as do the # 01 backpack
    for good in goods:
        for j in range(m, good.v - 1, -1): # Descending
            f[j] = max(f[j], f[j - good.v] + good.w)

    print(f[m])

Optimization Method two: Monotone queue optimization

4 mixed knapsack problem

There are N kinds of goods and a backpack capacity of V. There are three categories of goods:

  • The first article can only be used once (backpack 01);
  • The second type article can be unlimited (full backpack);
  • The third article can only use up si times (multiple backpack);

Each volume is vi, the value is wi. Which solving the items into the backpack, can not exceed the total volume of the article capacity of the backpack, and the sum of the maximum value. The maximum output value.

Resolution:

  • Convert multiple backpack to backpack 01.
  • Then 01 minutes backpack and backpack full transfer of two categories.
from collections import namedtuple

def func(v, w, s, m):  # V volume, the value of W, the number of s, m total volume
    Good = namedtuple('Good', ['kind', 'v', 'w'])
    f = [0]*(m+1)
    goods = []
    for i in range(len(w)):
        if s[i] < 0:  # 01 backpack
            goods.append(Good(-1, v[i], w[i]))
        elif s[i] == 0: # Full backpack
            goods.append(Good(0, v[i], w[i]))
        else:  # 01 Multi-turn backpack backpack
            k = 1
            while k <= s[i]:
                s[i] -= k
                goods.append(Good(-1, k*v[i], k*w[i]))
                k *= 2
            if s[i] >0: goods.append(Good(-1, s[i]*v[i], s[i]*w[i]))
    
    # Transfer to a different type of knapsack problem
    for good in goods:
        if good.kind == -1:  # 01 backpack
            for j in range(m, good.v-1, -1):
                f[j] = max(f[j], f[j - good.v] + good.w)
        else:  # Full backpack
            for j in range(good.v, m+1):
                f[j] = max(f[j], f[j - good.v] + good.w)
    print(f[m])

5-D expenses knapsack problem

There are N items V and a capacity of the backpack, the backpack can withstand the maximum weight of M. Each itemIt can only be used oncevolumeIs vi,weightIs mi, value is wi.

What will solve the items into backpacks, make goodsCapacity does not exceed the total volume of the backpackNot exceed the maximum weight of the total weight of the backpack can withstandAnd the sum of the maximum value. The maximum output value.

Resolution:

f[i][j] It represents the volume is i, the maximum value of the weight of the backpack when j.

To enumerate items, then the volume of the enumeration, and then enumerated by weight.Because the backpack 01, the volume and weight descending enumeration.

def func(v, w, m, V, M): #v volume, w value, m wt, V the total volume, M total weight
    f = [[0]*(M+1) for _ in range(V+1)]
    for i in range(1, len(w)+1):  
        for j in range(V, v[i-1]-1, -1):
            for k in range(M, m[i-1]-1, -1):
                f[j][k] = max(f[j][k], f[j-v[i-1]][k-m[i-1]] + w[i-1])
    print(f[V][M])

6 packet knapsack problem

There are N items and a group V of the capacity of the backpack. Each group has a number of items, selected from a maximum of one article in the same group.

The volume of each item is vij, is a value wij, where ii is the group number, j is the group number.

Which solving the items into the bag, the total volume of the article can not exceed the capacity of the backpack, and the total value of the maximum. The maximum output value.

Resolution:

State transition

for i in [1, n]: # Item Total
	 for j in [m, v]: # Volume descending Enumeration 
		f[j] = max(f[j], f[j-v[0]]++w[0], f[j-v[1]]++w[1], ...)

Means that the last layer of articles of this group can not chosen, may be selected from the first, may be selected from the second, third ... first selected, taking the maximum.

def func(v, w, m): # V packet volume [[v1. V2], [v1]], w packet value [[w1, w2], [w1]], m total volume
    f = [0]*(m+1)
    for i in range(len(w)):  # Enumerate each group
        for j in range(m, -1, -1): # Volume [m, 0]
            for k in range(0, len(v[i])): Number # 
                if j >= v[i][k]:
                    f[j] = max(f[j], f[j - v[i][k]] + w[i][k])
    print(f[m])

7 knapsack problem several programs seeking

There are N items V and a capacity of the backpack. Each item can only be used once. Volume is the i-th items vi, a value wi.

Which solving the items into the bag, the total volume of these items can not exceed the capacity of the backpack, and the total value of the maximum.

ExportThe most preferred embodiment of the method the number of. Note that the answer may be large, please answer the output module 10 ^ 9 + 7.

Resolution:

f[i] It represents the volumeExactly i The maximum value of the backpack in case.

g[i] It represents the volume of the case the number i of the program.

  • If the current value is equal to take and not take one decision, theng[i] Wherein the number is equal to one embodiment
  • If the current value is equal to take and not to take two kinds of decision-making, theng[i]It is equal to the sum of two programs and
    Notef In addition to all the initializationf[0] Have set -INF, we ask for the maximum value of the case is just the volume of i's. Otherwise, i is less than equal to the volume of the greatest value, not so good statistics program.
def func(v, w, m): # M total weight
    f = [float('-inf')]*(m+1)
    g = [0]*(m+1)
    f[0] = 0
    g[0] = 1  Program volume number # 0 is 1
    for i in range(1, len(w)+1):  # Item [1, n]
        for j in range(m, v[i-1]-1, -1):  # Volume [m, v [i]]
            t = max(f[j], f[j - v[i-1]] + w[i-1])  Remove the maximum #
            s = 0
            if t == f[j]: s = (s+g[j])%mod  # If the maximum value is equal to f [j], then add g [j]
            if t == f[j - v[i-1]] + w[i-1]: s= (s + g[j - v[i-1]])%mod  # If the maximum value is equal to f [j-v [i-1]] + w [i-1], then add g [[j-v [i-1]]
            f[j], g[j] = t, s
    maxw = max(f)
    res = 0
    for i in range(len(f)):
        if f[i] == maxw:
           res = (res + g[i])%mod
    print(res)

8 seek knapsack problem solution

9 have knapsack problem dependent

There dependencies between items.

Intelligent Recommendation

01 backpack + full backpack + multiple backpacks

problem: 1. 01 backpack: give you n different items, each item has its own weight [i], and value [i],If there is only one itemHow can I get the most value for a backpack with a capacity of V? --------...

-01 knapsack problem knapsack full backpack, multiple backpack

-01 knapsack problem knapsack full backpack, multiple backpack 01 Backpack: concept: There Goods_Num items, MAX_Volume the maximum load capacity,Only one of each item, Each item has a corresponding we...

01 classic knapsack problem knapsack full backpack + + multiple backpack

Editor:   01 backpack There are n different items, each item has two attributes, size volume, value value, now give a backpack w capacity, the maximum number of Q-value items can be taken away. F...

01 backpack problem, complete backpack, multiple backpacks, just full

01 backpack problem: The most basic backpack problem, each item can only be placed once. Complete backpack problem: Each item can be put more unlimited. Multiple backpack issues: Each item has a fixed...

Backpack summary (01 backpack, full backpack, multiple backpacks)

Recent study summary The study of dynamic programming is close to the end. Although we have only studied some furs, we have not made in-depth contact, and the questions are all basic examples, but I s...

More Recommendation

Backpack summary (01 backpack + full backpack + multiple backpacks)

First compare the next three questions! ! 【01 Backpack】 Give you n different items, each item has its own weight w[i], and value v[i]. If each item can only be taken once and give you a backpack with ...

The knapsack problem (01 backpack) (full backpack)

01 backpack There are N items V and a capacity of the backpack. Each item can onlyUsed once。 i-volume items is vi, a value wi. which items will be solved into the backpack, the total volume of these i...

Backpack problem 2 Multiple backpacks, mixed backpacks

Multiple backpack  There is a backpack with a total volume of V, there are n items, and the volume is v i v_i vi​, The value is w i w_i wi​, The quantity is c i c_i ci​, How to get the maximum vo...

Algorithm-backpack problem 01 backpack + complete backpack + multiple backpacks

01 backpack: https://biancheng.love/problem/51/index There are n different items, each item has two attributes,weight, value , now give a backpack with a capacity of w, askThe maximum value of items t...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top