HDU - 1114
限制容量恰好为W的完全背包。
那就设dp[j]为容量为j恰好能得到的最小价值,不存在则设为INF
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 #define INF 0x3f3f3f3f 6 #define MOD 1000000007 7 using namespace std; 8 typedef long long LL; 9 10 const int maxn = 5e2 + 5; 11 const int maxw = 1e4 + 5; 12 int p_w, tot_w, W; 13 int N; 14 int val[maxn], wei[maxn]; 15 int dp[maxw]; 16 int T; 17 18 void solve() { 19 memset(dp, INF, sizeof(dp)); 20 dp[0] = 0; // 21 for (int i = 0; i < N; i++) { 22 for (int j = wei[i]; j <= W; j++) { 23 dp[j] = min(dp[j], dp[j - wei[i]] + val[i]); 24 } 25 } 26 if (dp[W] == INF) { 27 puts("This is impossible."); 28 } else { 29 printf("The minimum amount of money in the piggy-bank is %d.\n", dp[W]); 30 } 31 } 32 33 int main(int argc, const char * argv[]) { 34 scanf("%d", &T); 35 while (T--) { 36 scanf("%d%d", &p_w, &tot_w); 37 W = tot_w - p_w; 38 scanf("%d", &N); 39 for (int i = 0; i < N; i++) { 40 scanf("%d%d", &val[i], &wei[i]); 41 } 42 solve(); 43 } 44 return 0; 45 }