Advertisement
shabbyheart

Fractional Knapsack

Dec 14th, 2019
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. double profit[10000],weight[1000],w_taken[10000];
  4. int n,u;
  5. class knapsack{
  6. public:
  7.     void input()
  8.     {
  9.         cin>>n>>u;
  10.         for(int i=0; i<n; i++)
  11.         {
  12.             cin>>profit[i]>>weight[i];
  13.         }
  14.     }
  15.     void solution()
  16.     {
  17.         selection_sort();
  18.         int i;
  19.         for( i =0 ;i<n; i++)
  20.         {
  21.             if(weight[i] > u)
  22.                 break;
  23.             w_taken[i] = 1;
  24.             u-=weight[i];
  25.         }
  26.         if(u!=0 && i<n)
  27.         {
  28.             w_taken[i] = u/weight[i];
  29.         }
  30.         profit_calculation();
  31.  
  32.     }
  33.     void profit_calculation()
  34.     {
  35.         double sum = 0;
  36.         for(int i=0; i<n; i++)
  37.         {
  38.             sum += w_taken[i]*profit[i];
  39.         }
  40.         cout<<sum;
  41.     }
  42.     void selection_sort()
  43.     {
  44.         for(int i =0; i<n-1; i++)
  45.         {
  46.             int max_index = i;
  47.             for(int j = i+1; j<n; j++)
  48.             {
  49.                 if( profit[j]/weight[j] > profit[max_index]/weight[max_index])
  50.                     max_index = j;
  51.             }
  52.             swap(profit[max_index],profit[i]);
  53.             swap(weight[max_index],weight[i]);
  54.         }
  55.     }
  56. };
  57. int main()
  58. {
  59.     freopen("input.txt","r",stdin);
  60.     knapsack fk;
  61.     fk.input();
  62.     fk.solution();
  63.  
  64. }
  65.  
  66. /*
  67. input:
  68. 4 70
  69. 30 10
  70. 280 40
  71. 180 20
  72. 80 10
  73.  
  74. ans 540
  75. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement