HDU 1114 Piggy-Bank(完全背包)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1114

题目大意:根据储钱罐的重量,求出里面钱最少有多少。给定储钱罐的初始重量,装硬币后重量,和每个对应面值硬币的重量。

Sample Input
3
10 110
2
1 1
30 50
10 110
2
1 1
50 30
1 6
2
10 3
20 4
 
Sample Output
The minimum amount of money in the piggy-bank is 60.
The minimum amount of money in the piggy-bank is 100.
This is impossible.
 
分析:这道题目的动态规划思想很简单,就是背包。
  
代码如下:
 # include<stdio.h>
# include<string.h>
const int N = ;
const int INF = 0xffffff;
int f[]; //f[i]表示总重量为i的硬币,价值为多少
int p[N],w[N];
int main()
{
int T;
scanf("%d",&T);
while (T--){
int n,a,b,i,j;
scanf("%d%d",&a,&b);
f[] = ; //表示重量为0的硬币价值为0
for (i=;i<=b;i++) f[i]=INF;
scanf("%d",&n);
for (i=;i<=n;i++) scanf("%d%d",&p[i],&w[i]);
for (i=;i<=n;i++){
for (j=w[i];j<=b-a;j++){
if (f[j-w[i]]+p[i]<f[j]) f[j]=f[j-w[i]]+p[i];
}
}
if (f[b-a]==INF) printf("This is impossible.\n");
else printf("The minimum amount of money in the piggy-bank is %d.\n",f[b-a]);
}
return ;
}
上一篇:题解报告:hdu 1114 Piggy-Bank(完全背包恰好装满)


下一篇:HDU 1114 Piggy-Bank ——(完全背包)