hdu 1114 Piggy-Bank(完全背包问题)

解题思路:完全背包问题,注意要将数组全部初始化一个足够大的数,要不然会影响递推式。

                 简单介绍一下递推思路,就是对每一件物品分为取一件取多件和不取。然后取多件和取一件都可以合并,  即取了一次再取一次~

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define inf 0x3f3f3f3f
int val[505];
int weight[505];
int dp[10005];
int main()
{
    //freopen("test.txt","r",stdin);
    int t,i,j;
    int e,f;        //empty->e  filled->f
    int n;          //kinds of coins
    scanf("%d",&t);
    while(t--)
    {
        memset(dp,0x3f,sizeof(dp));
        scanf("%d%d",&e,&f);
        scanf("%d",&n);
        int W = f-e;
        for(i=0;i<n;i++)
        {
            scanf("%d%d",&val[i],&weight[i]);
        }
        //for(i=1;i<=W;i++)
        //    dp[i]=inf; dp[0]=0;
        for(i=0;i<n;i++)
        {
            for(j=weight[i];j<=W;j++)
            {

                dp[j] = min(dp[j],dp[j-weight[i]]+val[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]);

        }
    }
    //cout << "Hello world!" << endl;
    return 0;
}

你可能感兴趣的:(ACM,HDU,完全背包)