「暑期訓練」「基礎DP」 Piggy-Bank (HDU-1114)

題意與分析

完全揹包問題。
算法揹包九講裏面都有提到過,我自己再說下對完全揹包的理解。
爲什麼01揹包中遍歷狀態從V0 ?考慮一下基本方程dp[i][j]=max(dp[i1][jw[i]]+v[i],dp[i1][j]) ,如果順序,那麼決定dp[i][j] 的就是dp[i][jw[i]] 而不是dp[i1][jw[i]] 了。

然而, 完全揹包的方程爲dp[i][j]=max{dp[i1][jkw[i]]+kv[i]} 。換句話說,在我們考慮第i件物品的時候,我們總是要多一種考慮的情況:再選一件第i個物品。因此,我們需要從dp[i][jw[i]] 推出dp[i][j] 。這樣,滾動數組的道理依然成立。

代碼

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#define MP make_pair
#define PB push_back
#define fi first
#define se second
#define ZERO(x) memset((x), 0, sizeof(x))
#define ALL(x) (x).begin(),(x).end()
#define rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define per(i, a, b) for (int i = (a); i >= (b); --i)
#define QUICKIO                  \
    ios::sync_with_stdio(false); \
    cin.tie(0);                  \
    cout.tie(0);
using namespace std;

template<typename T>
T read()
{
    T tmp; cin>>tmp;
    return tmp;
}
int dp[10005];
int main()
{
QUICKIO
    int T; cin>>T;
    while(T--)
    {
        int e,f; cin>>e>>f;
        int n; cin>>n;
        int w[505],v[505];
        rep(i,1,n)
            cin>>v[i]>>w[i];
        memset(dp,0x3f,sizeof(dp));
        int inf=dp[0];
        dp[0]=0;
        rep(i,1,n)
        {
            rep(j,0,f-e)
                if(j>=w[i])
                {
                    dp[j]=min(dp[j-w[i]]+v[i],dp[j]);
                }
        }
        if(dp[f-e]==inf) cout<<"This is impossible."<<endl;
        else cout<<"The minimum amount of money in the piggy-bank is "
                 <<dp[f-e]<<".\n";
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章