📜  重物背包

📅  最后修改于: 2021-04-29 18:04:33             🧑  作者: Mango

给定一个容量为C的背包,两个数组w []val []代表N个不同项目的权重和值,任务是找到可以放入背包的最大值。物品不能折断,重量为X的物品需要背包的X容量。

例子:

方法:传统的著名的0-1背包问题可以在O(N * C)时间内解决,但是如果背包的容量很大,则无法制作2D N * C阵列。幸运的是,可以通过重新定义dp的状态来解决。
首先让我们看一下DP的状态。

dp [V] [i]表示获得至少V的值所需的子数组arr [i…N-1]的最小权重子集。重复关系将是:

因此,对于从0每个VV可能的最大值,试图找到如果给定的V CAN用给定的阵列来表示。可以表示的最大此类V成为必需的答案。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
#define V_SUM_MAX 1000
#define N_MAX 100
#define W_MAX 10000000
  
// To store the states of DP
int dp[V_SUM_MAX + 1][N_MAX];
bool v[V_SUM_MAX + 1][N_MAX];
  
// Function to solve the recurrence relation
int solveDp(int r, int i, int* w, int* val, int n)
{
    // Base cases
    if (r <= 0)
        return 0;
    if (i == n)
        return W_MAX;
    if (v[r][i])
        return dp[r][i];
  
    // Marking state as solved
    v[r][i] = 1;
  
    // Recurrence relation
    dp[r][i]
        = min(solveDp(r, i + 1, w, val, n),
              w[i] + solveDp(r - val[i],
                             i + 1, w, val, n));
    return dp[r][i];
}
  
// Function to return the maximum weight
int maxWeight(int* w, int* val, int n, int c)
{
  
    // Iterating through all possible values
    // to find the the largest value that can
    // be represented by the given weights
    for (int i = V_SUM_MAX; i >= 0; i--) {
        if (solveDp(i, 0, w, val, n) <= c) {
            return i;
        }
    }
    return 0;
}
  
// Driver code
int main()
{
    int w[] = { 3, 4, 5 };
    int val[] = { 30, 50, 60 };
    int n = sizeof(w) / sizeof(int);
    int C = 8;
  
    cout << maxWeight(w, val, n, C);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG 
{
    static final int V_SUM_MAX = 1000;
    static final int N_MAX = 100;
    static final int W_MAX = 10000000;
      
    // To store the states of DP 
    static int dp[][] = new int[V_SUM_MAX + 1][N_MAX]; 
    static boolean v[][] = new boolean [V_SUM_MAX + 1][N_MAX]; 
      
    // Function to solve the recurrence relation 
    static int solveDp(int r, int i, int w[],       
                          int val[], int n) 
    { 
        // Base cases 
        if (r <= 0) 
            return 0; 
              
        if (i == n) 
            return W_MAX; 
              
        if (v[r][i]) 
            return dp[r][i]; 
      
        // Marking state as solved 
        v[r][i] = true; 
      
        // Recurrence relation 
        dp[r][i] = Math.min(solveDp(r, i + 1, w, val, n), 
                     w[i] + solveDp(r - val[i], 
                                    i + 1, w, val, n)); 
          
        return dp[r][i]; 
    } 
      
    // Function to return the maximum weight 
    static int maxWeight(int w[], int val[], 
                         int n, int c) 
    { 
      
        // Iterating through all possible values 
        // to find the the largest value that can 
        // be represented by the given weights 
        for (int i = V_SUM_MAX; i >= 0; i--)
        { 
            if (solveDp(i, 0, w, val, n) <= c) 
            { 
                return i; 
            } 
        } 
        return 0; 
    } 
      
    // Driver code 
    public static void main (String[] args)
    { 
        int w[] = { 3, 4, 5 }; 
        int val[] = { 30, 50, 60 }; 
        int n = w.length; 
        int C = 8; 
      
        System.out.println(maxWeight(w, val, n, C)); 
    } 
}
  
// This code is contributed by AnkitRai01


Python3
# Python3 implementation of the approach
V_SUM_MAX = 1000
N_MAX = 100
W_MAX = 10000000
  
# To store the states of DP
dp = [[ 0 for i in range(N_MAX)]
          for i in range(V_SUM_MAX + 1)]
v = [[ 0 for i in range(N_MAX)]
         for i in range(V_SUM_MAX + 1)]
  
# Function to solve the recurrence relation
def solveDp(r, i, w, val, n):
      
    # Base cases
    if (r <= 0):
        return 0
    if (i == n):
        return W_MAX
    if (v[r][i]):
        return dp[r][i]
  
    # Marking state as solved
    v[r][i] = 1
  
    # Recurrence relation
    dp[r][i] = min(solveDp(r, i + 1, w, val, n), 
            w[i] + solveDp(r - val[i], i + 1,
                            w, val, n))
    return dp[r][i]
  
# Function to return the maximum weight
def maxWeight( w, val, n, c):
  
    # Iterating through all possible values
    # to find the the largest value that can
    # be represented by the given weights
    for i in range(V_SUM_MAX, -1, -1):
        if (solveDp(i, 0, w, val, n) <= c):
            return i
  
    return 0
  
# Driver code
if __name__ == '__main__':
    w = [3, 4, 5]
    val = [30, 50, 60]
    n = len(w)
    C = 8
  
    print(maxWeight(w, val, n, C))
  
# This code is contributed by Mohit Kumar


C#
// C# implementation of the approach
using System;
  
class GFG 
{
    static readonly int V_SUM_MAX = 1000;
    static readonly int N_MAX = 100;
    static readonly int W_MAX = 10000000;
      
    // To store the states of DP 
    static int [,]dp = new int[V_SUM_MAX + 1, N_MAX]; 
    static bool [,]v = new bool [V_SUM_MAX + 1, N_MAX]; 
      
    // Function to solve the recurrence relation 
    static int solveDp(int r, int i, int []w,     
                       int []val, int n) 
    { 
        // Base cases 
        if (r <= 0) 
            return 0; 
              
        if (i == n) 
            return W_MAX; 
              
        if (v[r, i]) 
            return dp[r, i]; 
      
        // Marking state as solved 
        v[r, i] = true; 
      
        // Recurrence relation 
        dp[r, i] = Math.Min(solveDp(r, i + 1, w, val, n), 
                     w[i] + solveDp(r - val[i], 
                                    i + 1, w, val, n)); 
          
        return dp[r, i]; 
    } 
      
    // Function to return the maximum weight 
    static int maxWeight(int []w, int []val, 
                         int n, int c) 
    { 
      
        // Iterating through all possible values 
        // to find the the largest value that can 
        // be represented by the given weights 
        for (int i = V_SUM_MAX; i >= 0; i--)
        { 
            if (solveDp(i, 0, w, val, n) <= c) 
            { 
                return i; 
            } 
        } 
        return 0; 
    } 
      
    // Driver code 
    public static void Main(String[] args)
    { 
        int []w = { 3, 4, 5 }; 
        int []val = { 30, 50, 60 }; 
        int n = w.Length; 
        int C = 8; 
      
        Console.WriteLine(maxWeight(w, val, n, C)); 
    } 
}
  
// This code is contributed by 29AjayKumar


输出:
90

时间复杂度: O(V_sum * N),其中V_sum是数组val []中所有值的总和。