01 knapsack problem dynamic programming

0-1 backpack
Description
Given n (n <= 100) kinds of goods and a backpack. I is the weight of the article of wi, the value of vi, knapsack capacity C (C <= 1000). Q: How should select the items into the backpack, the backpack into the total value of the largest items in the selection of the items into the backpack, for each item i have only two choices:? Load or no load. I article can not be loaded several times, only part of the article can not be charged i.
Input
A total of n + 1 line: first row n and the value of c, n represents items and knapsack capacity c; next n lines, each line has two data represent the first i (1≤i≤n) member the weight and value of the items.
Output
The total value of the maximum output load backpack items.
 
Sample Input 1
5 10 2 6 2 3 6 5 5 4 4 6
Sample Output 1
15
 
 
analysis:
  there are n items is n, c is the bag space
 
  Provided dp [i] [j] for the i-th item selected in the front space of the backpack j, the maximum load value, initializing: 0 boundary is initialized to 0, the answer dp [n] [c]
  If the current installed under j j> = obj_weight , equation of state:
  dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - obj_weight] + obj_price);
  If the current j fit, equation of state:
  dp[i][j] = dp[i - 1][j];
 
#include <iostream>
using namespace std;

#define NUM 1000

int DP [NUM] [NUM];

int max(int a, int b) {
    return a > b ? a : b;
}
int main () {
     int n-; // n-th article 
    int C; // backpack capacity 
    CIN >> >> n- C;
     int   weight_price_table [ 100 ] [ 2 ];
    
    for (int i = 1; i <= n; i++) {
        cin >> weight_price_table[i][0] >> weight_price_table[i][1];
    }
    
    // Initialization boundary when i = 0, j = 0 = 0 when DP 
    for ( int I = 0 ; I <NUM; I ++ ) {
        dp[0][i] = 0;
        dp[i][0] = 0;
    }


    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= c; j++) {
            int obj_weight = weight_price_table[i][0];
            int obj_price = weight_price_table[i][1];
            if (j >= obj_weight) {//如果装得下
                dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - obj_weight] + obj_price);
            }
            the else { // fit 
                DP [I] [J] DP = [I - . 1 ] [J];
            }
            
        }
    }

    cout << dp[n][c];



}

 

 

Guess you like

Origin www.cnblogs.com/likeghee/p/11770388.html