【HDOJ】1114 Piggy-Bank

DP,先将coins按照重量排序可以优化。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define MAXNUM  10005
 5 #define COINNUM 505
 6 #define MAXVAL  0x7fffffff
 7 #define MYMIN(a, b) a<b ? a:b
 8 
 9 typedef struct {
10     int weight, val;
11 } coin_st;
12 
13 coin_st coins[COINNUM];
14 int dp[MAXNUM];
15 int e, f;
16 
17 int comp(const void *a, const void *b) {
18     return ((coin_st*)a)->weight - ((coin_st*)b)->weight;
19 }
20 
21 int main() {
22     int case_n, n;
23     int i, j, left;
24 
25     scanf("%d", &case_n);
26     dp[0] = 0;
27     while (case_n--) {
28         scanf("%d %d", &e, &f);
29         scanf("%d", &n);
30         for (i=0; i<n; ++i)
31             scanf("%d %d", &coins[i].val, &coins[i].weight);
32         qsort(coins, n, sizeof(coin_st), comp);
33 
34         for (i=1; i<=f-e; ++i) {
35             dp[i] = MAXVAL;
36             for (j=0; j<n; ++j) {
37                 left = i-coins[j].weight;
38                 if (left<0)
39                     break;
40                 if (dp[left]!=MAXVAL && dp[left]+coins[j].val < dp[i])
41                     dp[i] = dp[left]+coins[j].val;
42             }
43         }
44         if (dp[f-e] == MAXVAL)
45             printf("This is impossible.\n");
46         else
47             printf("The minimum amount of money in the piggy-bank is %d.\n", dp[f-e]);
48     }
49 
50     return 0;
51 }

 

posted on 2014-04-01 17:08  Bombe  阅读(188)  评论(0编辑  收藏  举报

导航