题目地址:点击打开链接
思路:完全背包,选重量重但是价值小的,二维的写废了,有时间一定再写一下
AC代码:
#include<stdio.h> #include<string.h> int value[510],weight[510]; int dp[10010]; #define MAX 1001000//这不能加分号 int min(int a,int b) { return a < b ? a : b; } int main() { int t,e,f,n,i,j; scanf("%d",&t); while(t--) { memset(dp,0,sizeof(dp)); scanf("%d%d%d",&e,&f,&n); for(i=0; i<n; i++) { scanf("%d%d",&value[i],&weight[i]); } //for(i=0; i<n; i++)这里是f-e for(i=0; i<=f-e; i++) { dp[i] = MAX; } dp[0] = 0; for(i=0; i<n; i++) { for(j=weight[i]; j<=f-e; j++) { dp[j] = min(dp[j],dp[j-weight[i]] + value[i]); } } if(dp[f-e] == MAX) printf("This is impossible.\n"); else printf("The minimum amount of money in the piggy-bank is %d.\n",dp[f-e]); } return 0; }