RQNOJ 2开心的金明(0/1背包)

 1 /*
 2 *  0/1背包 
 3 */
 4 #include <cstdio>
 5 #include <cstring>
 6 #include <iostream>
 7 
 8 using namespace std;
 9 
10 const int M = 30;
11 const int N = 30005;
12 
13 int f[N];
14 struct pack {
15     int cost;
16     int value;
17 }p[M];
18 
19 void ZeroOnePack(int n, int cost, int value) {
20     for (int i=n; i>=cost; --i) {
21         if (f[i] < f[i-cost]+value) f[i] = f[i-cost] + value;
22     }
23 }
24 
25 int dp(int n, int m) {
26     memset(f, 0, sizeof(f));
27     for (int i=0; i<m; ++i) {
28         ZeroOnePack(n, p[i].cost, p[i].value);
29     }
30     return f[n];
31 }
32 
33 int main() {
34     int n, m, d;
35     while (scanf("%d%d", &n, &m) != EOF) {
36         for (int i=0; i<m; ++i) {
37             scanf ("%d%d", &p[i].cost, &d);
38             p[i].value = p[i].cost * d;
39         } 
40         int ans = dp(n, m);
41         printf ("%d\n", ans);
42     }
43     return 0;
44 }

 

posted on 2012-05-16 20:33  Try86  阅读(166)  评论(0)    收藏  举报