Advertisement
dipBRUR

24

Nov 20th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. // Problem : 0-1 Knapshack with solution print
  2. int cost[100];
  3. int weight[100];
  4. int dp[100][1000];
  5. int dir[100][1000];
  6. int KnapShack(int i, int w) {
  7. if (i == n+1)
  8. return 0;
  9. int &ret = dp[i][w];
  10. if (ret != -1)
  11. return ret;
  12. int profit1 = 0;
  13. int profit2 = 0;
  14. if (w + weight[i] <= cap)
  15. profit1 = cost[i] + KnapShack(i+1, w + weight[i]);
  16. else
  17. profit1 = 0;
  18. profit2 = KnapShack(i+1, w);
  19. if (profit1 > profit2) {
  20. dir[i][w] = 1;
  21. return ret = profit1;
  22. }
  23. else {
  24. dir[i][w] = 2;
  25. return ret = profit2;
  26. }
  27. }
  28. void printSol(int i, int w) {
  29. // base case
  30. if (i == n+1)
  31. return;
  32. // or
  33. // if (dir[i][w] == -1)
  34. // return;
  35. if (dir[i][w] == 1) {
  36. cout << i << " -> " << cost[i] << endl;
  37. printSol(i+1, w+weight[i]);
  38. }
  39. else {
  40. printSol(i+1, w);
  41. }
  42. }
  43.  
  44. // Call : KnapShack(1, 0)
  45.  
  46. // Bit Mask
  47. int count_one(int mask) { return __builtin_popcount(mask); }
  48. int Set(int N,int pos) { return N=N | (1<<pos); }
  49. int reset(int N,int pos) { return N= N & ~(1<<pos); }
  50. bool check(int N,int pos){ return (bool)(N & (1<<pos)); }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement