fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void printknapSack(int W, int wt[], int val[], int n)
  5. {
  6. int i, w;
  7. int K[n + 1][W + 1];
  8.  
  9. for (i = 0; i <= n; i++)
  10. {
  11. for (w = 0; w <= W; w++)
  12. {
  13. if (i == 0 || w == 0)
  14. {
  15. K[i][w] = 0;
  16. }
  17. else if (wt[i - 1] <= w)
  18. {
  19. K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
  20. }
  21. else
  22. {
  23. K[i][w] = K[i - 1][w];
  24. }
  25. }
  26. }
  27.  
  28. int res = K[n][W];
  29. cout <<endl<< "Max-Profit: " << res << endl;
  30. cout <<endl<< "The Items are: "<<endl<<endl;
  31.  
  32. w = W;
  33. for (i = n; i > 0 && res > 0; i--)
  34. {
  35. if (res == K[i - 1][w])
  36. continue;
  37. else
  38. {
  39. cout <<"Item Number: " <<i << " and Weight: "<<wt[i - 1] <<endl;
  40. res = res - val[i - 1];
  41. w = w - wt[i - 1];
  42. }
  43. }
  44. }
  45.  
  46. int main()
  47. {
  48. int nbag,wt,w;
  49. cout<<"Enter the number of bags: ";
  50. cin >> nbag;
  51. int values[nbag];
  52. cout<<"Enter the values: ";
  53. for(int i=0; i<nbag; i++){
  54. cin>> values[i];
  55. }
  56.  
  57. int weight[nbag];
  58. cout<<"Enter the weights of bags: ";
  59. for(int i=0; i<nbag; i++){
  60. cin>> weight[i];
  61. }
  62. cout<<"Enter the maximum weight of the bag: ";
  63. cin>>w;
  64.  
  65. int n = sizeof(values) / sizeof(values[0]);
  66.  
  67. printknapSack(w, weight, values, n);
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0.01s 5276KB
stdin
5
20 25 30 15 10
3  1  4  5  2
5
stdout
Enter the number of bags: Enter the values: Enter the weights of bags: Enter the maximum weight of the bag: 
Max-Profit: 55

The Items are: 

Item Number: 3 and Weight: 4
Item Number: 2 and Weight: 1