key:要取满,所以big[0] = 0;其他的都初始化为无穷~
#include <iostream> #include <stdio.h> #include <string.h> const int maxn = 1e4 + 5; const int INF = 1e7; int big[maxn]; using namespace std; int main() { int t; int e, f; int n; int p[500 + 5], w[500 + 5]; scanf("%d", &t); while(t--){ scanf("%d%d", &e, &f); scanf("%d", &n); for(int i = 1; i <= maxn; i++){ big[i] = INF; } big[0] = 0; for(int i = 1; i <= n; i ++){ scanf("%d%d", &p[i], &w[i]); } for(int i = 1; i <= n; i++){ for(int j = w[i]; j <= f - e; j++) if(big[j - w[i]] != INF) big[j] = min(big[j], big[j - w[i]] + p[i]); } if(big[f - e] != INF) printf("The minimum amount of money in the piggy-bank is %d. ", big[f - e]); else printf("This is impossible. "); } return 0; }