Advertisement
satishfrontenddev5

Untitled

Jan 6th, 2024
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. /*
  2. Given weights and values of N items, we have to put these items in a knapsack of capacity W in such a way that maximum capacity is used.
  3.  
  4. Note: It is allowed to break items for maximizing the total value of knapsack, i.e., it is not necessary to take the whole item.
  5.  
  6. Input format
  7. The first line contains 2 integers, N and W denoting the number of items and the capacity of the knapsack.
  8.  
  9. The second line contains N integers, with the i-th one representing the weight of the i-th item.
  10.  
  11. The third line again contains N integers, with the i-th number representing the value of the i-th item.
  12.  
  13. Output format
  14. Print a double value representing the maximum value that can be obtained with the given knapsack capacity.
  15.  
  16. The output would be considered correct upto 6 digits of precision.
  17.  
  18. Sample Input 1
  19. 3 4
  20.  
  21. 2 2 3
  22.  
  23. 100 10 120
  24.  
  25. Sample Output 1
  26. 180.00
  27.  
  28. Explanation
  29. Total maximum value of item we can have is 180.00 for the given capacity of sack by taking the whole of item 1 and (2/3)rd of item 3.
  30.  
  31. Constraints
  32. 1 <= N <= 100000
  33.  
  34. 1 <= W <= 100000
  35.  
  36. 1 <= weights[i] <= 200000
  37.  
  38. 1 <= values[i] <= 1000000000
  39.  
  40. Note: It is recommended to use double instead of float to store values in C++ submissions.
  41. */
  42. // TUF: https://www.youtube.com/watch?v=F_DDzYnxO14&t=1s
  43. double fractionalKnapsack
  44. (int N,int W,vector<int>&weights,vector<int>&values){
  45.     double maxValue=0;
  46.     double currentWeight=0;
  47.     double totalWeght=W;
  48.     priority_queue<pair<double,int> >pq;
  49.     int i,j;
  50.     for(i=0;i<N;i++){
  51.         double ratio=((values[i]*(1.0))/(weights[i]*1.0));
  52.         pq.push({ratio,i});
  53.     }
  54.     while(currentWeight<totalWeght){
  55.         auto top=pq.top();
  56.         int index=top.second;
  57.         double ratio=top.first;
  58.         if(currentWeight+weights[index]<=totalWeght){
  59.             currentWeight=currentWeight+weights[index];
  60.             maxValue=maxValue+values[index];
  61.         }else{
  62.             double remainingWeight=totalWeght-currentWeight;
  63.             maxValue=maxValue+(remainingWeight*ratio);
  64.             currentWeight=totalWeght;
  65.         }
  66.         pq.pop();
  67.     }
  68.  
  69.     return maxValue;
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement