Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. #include <math.h>
  6. #include <limits.h>
  7.  
  8. #define MAX 10
  9. #define TWOMAX 1024
  10.  
  11. int n; // Number of items
  12. int pown; // 2^n
  13. int cap; // Max weight it can hold
  14.  
  15. float wts[MAX]; // All the weights
  16. float vals[MAX]; // All the values
  17.  
  18. float mv = -1; // Maximum value
  19.  
  20. int mvals[MAX]; // Holds the max value combination
  21.  
  22. void input () {
  23.     std::cout<<"Enter the number of items: ";
  24.     std::cin >> n;
  25.     pown = pow(2, n);
  26.     int i;
  27.     for (i = 0; i < n; ++i) {
  28.         std::cout <<"Enter weight and value of item : "<< i+1;
  29.         std::cin >> wts[i] >> vals[i];
  30.     }
  31.     std::cout <<"Enter knapsack capacity: ";
  32.     std::cin >> cap;
  33. }
  34.  
  35. float getWeight (int incl[MAX]) {
  36.     int i;
  37.     float wt = 0;
  38.     for (i = 0; i < n; ++i) {
  39.         if (incl[i]) {
  40.             wt += wts[i];
  41.         }
  42.     }
  43.     return wt;
  44. }
  45.  
  46. float getValue (int incl[MAX]) {
  47.     int i;
  48.     float value = 0.0;
  49.     for (i = 0; i < n; ++i) {
  50.         if (incl[i]) {
  51.             value += vals[i];
  52.         }
  53.     }
  54.     return value;
  55. }
  56.  
  57. void findMax () {
  58.  
  59.     int i, j;
  60.     int k;
  61.  
  62.     int curr[MAX];
  63.  
  64.     for (i = 0; i < pow(2, n); ++i) {
  65.  
  66.         for (j = 0; j < n; ++j) {
  67.             curr[j] = (int)(i / (pow(2, j))) % 2;
  68.             // printf("%d", curr[j]);
  69.         }
  70.  
  71.         float v = getValue(curr);
  72.         float w = getWeight(curr);
  73.         // printf(" | %.2f, %.2f", w, v);
  74.  
  75.         if (w <= cap && v > mv) {
  76.             mv = v;
  77.             // printf(" | *");
  78.             for (j = 0; j < n; ++j) {
  79.                 mvals[j] = curr[j];
  80.             }
  81.         }
  82.  
  83.         // printf("\n");
  84.  
  85.     }
  86.  
  87. }
  88.  
  89. int main (int argc, char const * argv []) {
  90.    
  91.     int i;
  92.  
  93.     input();
  94.     findMax();
  95.  
  96.     std::cout <<"\nOptimal solution:\nWeight\t| Value\n";
  97.  
  98.     for (i = 0; i < n; ++i) {
  99.         if (mvals[i]) {
  100.         //std::cout << wts[i]<<"\t"<<vals[i];
  101.         }
  102.     }
  103.  
  104.     std::cout <<"\nMax value: "<<getValue(mvals);
  105.     std::cout <<"\n Weight fit: "<<getWeight(mvals);
  106.  
  107.     return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement