Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2014
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5. #include <ctype.h>
  6. #include <algorithm>
  7. #include <vector>
  8. #include <map>
  9. #include <set>
  10. #include <iostream>
  11. #include <string>
  12. #include <queue>
  13. #include <stack>
  14.  
  15. #define sqr(x) (x*x)
  16. #define cube(x) (x*x*x)
  17. #define INF 999999999
  18. #define MOD 100000007
  19.  
  20. inline bool read(int &x){int c=getchar();int sgn=1;while(~c&&c<'0'||c>'9'){if(c=='-')sgn=-1;c=getchar();}for(x=0;~c&&'0'<=c&&c<='9';c=getchar())x=x*10+c-'0'; x*=sgn; return ~c;}
  21.  
  22. using namespace std;
  23.  
  24. struct knapsack {
  25.     int value,weight;
  26. }storage[510];
  27.  
  28. int k,n,dp_memo[2][2000010];
  29.  
  30. int main(){
  31.     //freopen("input.txt","r",stdin);
  32.  
  33.     while(read(k) && read(n)) {
  34.         for (int i=0; i<n; i++) {
  35.             read(storage[i].value);
  36.             read(storage[i].weight);
  37.         }
  38.  
  39.         int a=0,b=1;
  40.         for (int i=0; i<=n; i++) {
  41.             for (int w=0; w<=k; w++) {
  42.                 if (!w || !i)
  43.                     dp_memo[a][w]=0;
  44.                 else if (storage[i-1].weight<=w)
  45.                     dp_memo[a][w]=max(dp_memo[b][w-storage[i-1].weight]+storage[i-1].value,dp_memo[b][w]);
  46.                 else
  47.                     dp_memo[a][w]=dp_memo[b][w];
  48.             }
  49.  
  50.             swap(a,b);
  51.         }
  52.  
  53.         printf("%d\n",dp_memo[n%2][k]);
  54.     }
  55.  
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement