题意:知道储钱罐里的硬币重量和各种面值硬币对应的重量,若能确定其中硬币的最小总价值,输出最小总价值,否则输出This is impossible.
思路:需要注意最小总价值时硬币重量是否与已知相等的判断。
#include
int p[510], w[510];
int ans[10010];
int main()
{
#ifdef LOCAL
freopen("data.in", "r", stdin);
#endif
int t, e, f, n, weight, cur;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &e, &f);
weight = f - e;
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%d%d", &p[i], &w[i]);
ans[0] = 0;
for(int i = 1; i <= weight; i++)
ans[i] = 10000000;
for(int i = 0; i < n; i++)
for(int j = w[i]; j <= weight; j++)
{
cur = ans[j - w[i]] + p[i];
if(ans[j] > cur)//要取更小的值,而初始只有ans[0]=0,所以只有重量刚刚好时ans值改变
{
ans[j] = cur;
}
}
if(ans[weight] != 10000000)//ans值改变则找到重量刚刚好的最小硬币总价值
printf("The minimum amount of money in the piggy-bank is %d.\n", ans[weight]);
else printf("This is impossible.\n");
}
return 0;
}