Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define INF 1<<30
  4. #define MAX 10005
  5. #define FASTIO ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  6. typedef long long ll;
  7.  
  8. struct Item
  9. {
  10. int value, weight;
  11.  
  12. Item(int value, int weight) : value(value), weight(weight)
  13. {}
  14. };
  15.  
  16. bool cmp(struct Item a, struct Item b)
  17. {
  18. double r1 = (double) a.value / a.weight;
  19. double r2 = (double) b.value / b.weight;
  20.  
  21. return r1 > r2;
  22. }
  23.  
  24. double fractionalKnapsack(int W, struct Item ar[], int n)
  25. {
  26. sort(ar, ar+n, cmp);
  27.  
  28. int curWeight = 0;
  29. double finalValue = 0.0;
  30.  
  31. for(int i = 0; i < n; i++){
  32. if(curWeight+ar[i].weight <= W){
  33. curWeight += ar[i].weight;
  34. finalValue += ar[i].value;
  35. }
  36. else{
  37. int remain = W - curWeight;
  38. finalValue += ar[i].value *( (double) remain/ar[i].weight );
  39. break;
  40. }
  41. }
  42.  
  43. return finalValue;
  44. }
  45.  
  46.  
  47. int main()
  48. {
  49. FASTIO
  50. ///*
  51. //double start_time = clock();
  52. #ifndef ONLINE_JUDGE
  53. freopen("in.txt", "r", stdin);
  54. freopen("out.txt", "w", stdout);
  55. freopen("error.txt", "w", stderr);
  56. #endif
  57. //*/
  58.  
  59. int W = 50; // Weight of knapsack
  60. Item arr[] = {{60, 10}, {100, 20}, {120, 30}};
  61.  
  62. int n = sizeof(arr) / sizeof(arr[0]);
  63.  
  64. cout << "Maximum value we can obtain = "
  65. << fractionalKnapsack(W, arr, n);
  66. return 0;
  67.  
  68. //double end_time = clock();
  69. //printf( "Time = %lf ms\n", ( (end_time - start_time) / CLOCKS_PER_SEC)*1000);
  70.  
  71. return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement