http://poj.org/gotoproblem?pid=1384

普通的完全背包问题,稍微注意:

                                 for(j=w[i];j<=f-e;j++)

具体代码:

View Code
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int Inf = (1<<29);
int t, e, f, n;
int p[550], w[550];
int dp[10100];
int main()
{
    int i, j, k;
    while(scanf("%d", &t)!=EOF)
    {
        while(t--)
        {
            scanf("%d%d%d", &e, &f, &n);
            for(i=1;i<=n;i++)
                scanf("%d%d", &p[i], &w[i]);
            for(i=0;i<=f-e;i++) dp[i]=Inf;
            dp[0]=0;
            for(i=1;i<=n;i++)
                for(j=w[i];j<=f-e;j++)
                    dp[j]=min(dp[j], dp[j-w[i]]+p[i]);
            if(dp[f-e]!=Inf)
                printf("The minimum amount of money in the piggy-bank is %d.\n", dp[f-e]);
            else printf("This is impossible.\n");
        }
    }
    return 0;
}