http://acm.hdu.edu.cn/showproblem.php?pid=1114
这个题一开始看到首先想到贪心。。。后来发现不对,是完全背包问题。。
状态转移方程为:dp[j] = min(dp[j-w[i]]+f[i],dp[j])
其中,dp[j]是重量为j的时候最小价值,w[i]为第i个物品重量,f[i]为第i个物品的价值
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#define MAXX 99999999
using namespace std;
int dp[10010];
int main()
{
int f[510],w[510];
int t,m,n,i,j,e,fq,weight;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&e,&fq);
scanf("%d",&n);
weight = fq - e;
for(i = 0; i < n; i++)
{
scanf("%d%d",&f[i],&w[i]);
}
for(i = 0; i <= weight; i++)
{
dp[i] = MAXX;
}
dp[0] = 0;
for(i = 0; i < n; i++)
{
for(j = w[i]; j <= weight; j++)
{
dp[j] = min(dp[j-w[i]]+f[i],dp[j]);
}
}
if(dp[weight] == MAXX)
{
printf("This is impossible.\n");
}
else
{
printf("The minimum amount of money in the piggy-bank is %d.\n",dp[weight]);
}
}
return 0;
}