Advertisement
fayeakuzzamantonmoy

activity_selector

Aug 19th, 2019
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5. // A job has a start time, finish time and profit.
  6. struct Activitiy
  7. {
  8.     int start, finish;
  9. };
  10.  
  11. // A utility function that is used for sorting
  12. // activities according to finish time
  13. bool activityCompare(Activitiy s1, Activitiy s2)
  14. {
  15.     return (s1.finish < s2.finish);
  16. }
  17.  
  18. // Returns count of the maximum set of activities that can
  19. // be done by a single person, one at a time.
  20. void printMaxActivities(Activitiy arr[], int n)
  21. {
  22.     // Sort jobs according to finish time
  23.     sort(arr, arr + n, activityCompare);
  24.  
  25.     cout << "Following activities are selected ";
  26.  
  27.     // The first activity always gets selected
  28.     int i = 0;
  29.     cout << "(" << arr[i].start << ", " << arr[i].finish << "), ";
  30.  
  31.     // Consider rest of the activities
  32.     for (int j = 1; j < n; j++)
  33.     {
  34.         // If this activity has start time greater than or
  35.         // equal to the finish time of previously selected
  36.         // activity, then select it
  37.         if (arr[j].start >= arr[i].finish)
  38.         {
  39.             cout << "(" << arr[j].start << ", "
  40.                  << arr[j].finish << "), ";
  41.             i = j;
  42.         }
  43.     }
  44. }
  45.  
  46. // Driver program
  47. int main()
  48. {
  49.  
  50.     int n;
  51.     cout << "enter the size of the array: ";
  52.     cin >> n;
  53.     Activitiy arr[n];
  54.     for (int i = 0; i < n; i++)
  55.     {
  56.         int a, b;
  57.         cout << "enter the start of pair " << i + 1 << " :";
  58.         cin >> a;
  59.         cout << "enter the finish of pair " << i + 1 << " :";
  60.         cin >> b;
  61.         arr[i] = {a, b};
  62.     }
  63.  
  64.     printMaxActivities(arr, n);
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement