HDU 2602 Bone Collector Bone Collector [01 Backpack]

Question link: https://vjudge.net/contest/103424#problem/A

 

Topic meaning:

Enter several sets of data in the first line, the first number in the second line represents the number of objects, and the second number represents the total volume. It should be noted that the value of the item is entered in the third row, and the volume of the item in the fourth row. Under the premise that objects cannot be split, what is the maximum value that can be obtained when the total volume of the backpack is known.

 

01 Backpack template question, nothing to say. (with two forms of dp array solutions)

 

 

//一维dp数组实现
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define max(a,b) ((a)>(b)?(a):(b))

intmain ()
{
    int t, n, m, i, j;
    int a[1005], b[1005];
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d%d", &n, &m);
        for (i = 0; i<n; i++)  
            scanf("%d", &a[i]);
        for (i = 0; i<n; i++)  
            scanf( " %d " , & b[i]);
         int dp[ 1005 ];        // The dp array always records the maximum value of the current volume         memset(dp, 0 , sizeof (dp)); 
         for (i = 0 ; i <n; i++)    // loop from the first for (j = m; j >= b[i]; j-- ) 

            
                dp[j] = max(dp[j], dp[j - b[i]] + a[i]);   // Compare the value after placing the i object with the value before not placing it, and record the larger value 
        printf ( " %d\n " , dp[m]);   // Enter the maximum value of the total volume     }
     return 0 ; 
 
}

 

 

 

// implementation of two-dimensional dp array
#include<iostream>
using namespace std;
int dp[1000][1000];
#define max(a,b) ((a)>(b)?(a):(b))

intmain ()
{
    int t, n, v, i, j;
    int va [ 1000 ], vo [ 1000 ];
    cin >> t;
    while (t--)
    {
        cin >> n >> v;
        for (i = 1; i <= n; i++)
            cin >> va[i];
        for (i = 1; i <= n; i++)
            cin >> vo[i];
        memset(dp, 0 , sizeof (dp)); // initialization operation
         for (i = 1 ; i <= n; i++ )
        {
            for (j = 0; j <= v; j++)
            {
                if (vo[i] <= j) // Indicates that the i-th item will be put into a knapsack of size j 
                    dp[i][j] = max(dp[i - 1 ][j], dp[i - 1 ][j - vo[i]] + va[i]);   // Compare the value after placing the i object with the value before not placing it, and record the larger value else // The i-th item cannot be placed in 
                    dp[ i][j] = dp[i - 1 ][j]; 
                 
            }
        }
        cout << dp[n][v] << endl;
    }
    return 0;
}

 

2018-04-27

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324981338&siteId=291194637