fork download
  1. #include <stdio.h>
  2. #include <algorithm>
  3. #include <string.h>
  4. #define MAX_N 1000
  5. #define MAX_W 1000
  6.  
  7. using namespace std;
  8.  
  9. int n;
  10. int dp[1002][40];
  11. int weight[MAX_W+1];
  12. int cost[MAX_N+1];
  13.  
  14. int knapsack(int i,int w, int cap)
  15. {
  16. if(i==n+1) return 0;
  17. if(dp[i][w]!=-1) return dp[i][w];
  18. int profit1=0,profit2=0;
  19. if(w+weight[i]<=cap)
  20. profit1=cost[i]+knapsack(i+1,w+weight[i],cap);
  21. profit2=knapsack(i+1,w,cap);
  22. dp[i][w]=max(profit1,profit2);
  23. return dp[i][w];
  24. }
  25.  
  26. int main()
  27. {
  28. int T ;
  29. int result[MAX_N];
  30. scanf("%d",&T);
  31. for(int j=0;j<T;j++)
  32. {
  33. int N;
  34. scanf("%d", &N);
  35. n = N;
  36. memset(weight,-1,sizeof(weight));
  37. memset(cost,-1,sizeof(cost));
  38. for(int nob=0; nob<N; nob++)
  39. {
  40. scanf("%d %d", &cost[nob], &weight[nob]);
  41. }
  42. int G, ans = 0;
  43. scanf("%d", &G);
  44. int CAP;
  45. while(G--)
  46. {
  47. scanf("%d", &CAP);
  48. memset(dp,-1,sizeof(dp));
  49. ans = ans + knapsack(0,0,CAP);
  50. }
  51. result[j] = ans;
  52.  
  53. }
  54.  
  55. for(int i=0;i<T;i++)
  56. {
  57. printf("%d\n", result[i]);
  58. }
  59.  
  60. }
Success #stdin #stdout 0s 3308KB
stdin
2
3
72 17
44 23
31 24
1
26
6
64 26
85 22
52 4
99 18
39 13
54 9
4
23
20
20
26
stdout
72
514