HDU - 1114 Piggy-Bank(完全背包讲解)

题意:背包重量为F-E,有N种硬币,价值为Pi,重量为Wi,硬币个数enough(无穷多个),问若要将背包完全塞满,最少需要多少钱,若塞不满输出“This is impossible.”。

分析:完全背包。

(1)构造二维数组:

dp[i][j]---背包重量为j时,前i种物品可得到的最大价值。

dp[i][j]=max{dp[i-1][j-k*W[i]]+k*P[i]|0<=k*W[i]<=F-E}

(2)构造滚动数组:(一维)

dp[j]---背包重量为j时,当前状态可得到的最大价值。

dp[j] = max(dp[j], dp[j - W[i]] + P[i]);(顺序枚举0~F-E)

原因:很显然,由于当前物品无穷多个,所以dp[j]的更新依赖于当前物品的dp[j - W[i]]的更新。

例如,背包重量为10。对于第一个物品,重量为3,价值为5,则dp[3]=5,而更新dp[6]时,dp[6]=max(dp[6],dp[6-3]+5)=10,已更新过的dp[3]相当于取一件第一个物品,因此dp[6]只需转移dp[3]的即可达到取两件第一个物品的目的。

对于本题,求最小值,因此dp[j] = min(dp[j], dp[j - W[i]] + P[i]);

又因背包要完全塞满,因此dp[0] = 0;这样可保证只有能将当前背包完全塞满的重量才可被更新为非INF。

还是上述例子,在研究装入第一件物品时,当更新dp[4]时,因为重量为3,显然只装第一件物品是塞不满重量为4的背包,所以dp[4]暂时不能被更新。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
    if(fabs(a - b) < eps) return 0;
    return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 500 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int P[MAXN], W[MAXN], dp[MAXT];
int main(){
    int T;
    scanf("%d", &T);
    while(T--){
        int E, F;
        scanf("%d%d", &E, &F);
        int w = F - E;
        int N;
        scanf("%d", &N);
        for(int i = 0; i < N; ++i){
            scanf("%d%d", &P[i], &W[i]);
        }
        memset(dp, INT_INF, sizeof dp);
        dp[0] = 0;
        for(int i = 0; i < N; ++i){
            for(int j = W[i]; j <= w; ++j){
                dp[j] = min(dp[j], dp[j - W[i]] + P[i]);
            }
        }
        if(dp[w] == INT_INF) printf("This is impossible.\n");
        else printf("The minimum amount of money in the piggy-bank is %d.\n", dp[w]);
    }
    return 0;
}

  

posted @ 2017-05-31 00:08  Somnuspoppy  阅读(285)  评论(0编辑  收藏  举报