题目链接。
分析:
该题的状态转移方程为:
f[v]=min{f[v],f[v-w[i]]+p[i]},将所有值初始化为无穷大
AC代码如下:
#include <stdio.h> #define MAXN 10010 const int INF = (1<<25); int dp[MAXN]; int main(){ int T, vol, vol1, vol2, n, i, w[550], p[550], j; scanf("%d", &T); while(T--){ scanf("%d %d", &vol1, &vol2); vol = vol2-vol1; scanf("%d", &n); for(i=0; i<n; i++) scanf("%d %d", &p[i], &w[i]); for(i=0; i<=vol; i++) dp[i] = INF; dp[0] = 0; for(i=0; i<n; i++){ for(j=w[i]; j<=vol; j++){ if(dp[j] > dp[j-w[i]]+p[i]) dp[j] = dp[j-w[i]]+p[i]; } } if(dp[vol] != INF) printf("The minimum amount of money in the piggy-bank is %d.\n", dp[vol]); else printf("This is impossible.\n"); } return 0; }