RQNOJ 15采药(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 N = 105;

11 const int M = 1005;

12 

13 int f[M];

14 struct pack {

15     int cost;

16     int value;

17 }p[N];

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;

35     while (scanf("%d%d", &n, &m) != EOF) {

36         for (int i=0; i<m; ++i) scanf ("%d%d", &p[i].cost, &p[i].value);

37         int ans = dp(n, m);

38         printf ("%d\n", ans);

39     }

40     return 0;

41 }

 

你可能感兴趣的:(背包)