HDU - 1074 DP (full backpack)

Piggy-Bank

Topic meaning:

T sets of data, each set of data has an n, representing n types of coins, first give you E, F, and then FE represents the total weight that the backpack can hold, and the value of n coins is given below w i and weight v i , Unlimited number of each, ask what is the minimum value of the backpack coins that can accommodate the weight of FE. If not, output This is impossible.

data range:

1 n 500 , 1 E F 10000 , 1 w i 50000 , 1 v i 10000.

Problem solving ideas:

The meaning of the question can be simplified as, the minimum value of a knapsack filled with W weight of n kinds of items, each with an infinite number, this is a complete knapsack problem, dp[j] represents the minimum value of a knapsack with a load of j, and the transfer equation is :

d p [ j ] = m a x ( d p [ j ] , d p [ j v [ i ] ] + w [ i ] )

See the code for details

AC code:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 10000;
const int INF = 1e9 + 7;
int dp[maxn + 5];
int E, F, W;
int T, n;
int w[505], v[505];
int main() {
    scanf("%d", &T);
    while(T--) {
        for(int i = 0; i <= maxn; i++)dp[i] = INF;//初始化为无穷大
        scanf("%d%d", &E, &F);
        W = F - E;//背包大小
        scanf("%d", &n);
        for(int i = 1; i <= n; i++)scanf("%d%d", &w[i], &v[i]);
        dp[0] = 0;
        for(int i = 1; i <= n; i++) {//虽然每个物体有无限个,但是对于第i个物体,dp[j]可由dp[j-v[i]]转移过来,就达到了取任意多个第i种物体之后的状态
            for(int j = v[i]; j <= W; j++) {
                dp[j] = min(dp[j], dp[j - v[i]] + w[i]);
            }
        }
        if(dp[W] == INF)printf("This is impossible.\n");//如果值未改变,说明不存在该状态
        else printf("The minimum amount of money in the piggy-bank is %d.\n", dp[W]);
    }
    return 0;
}

Guess you like

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