Advertisement
NB52053

Greedy

Nov 14th, 2017
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. Algo Lab #3 (Greedy algo_Practise)
  2.  
  3. #include<cstdio>
  4. #include<algorithm>
  5.  
  6. using namespace std;
  7.  
  8. #define SIZE 101
  9.  
  10. //int S[SIZE], E[SIZE];
  11.  
  12. struct Activity
  13. {
  14.     int startT, endT;
  15. };
  16.  
  17. Activity A[SIZE];
  18.  
  19.  
  20. bool operator<(const Activity &lhs, const Activity &rhs)
  21. {
  22.     return lhs.endT < rhs.endT;
  23. }
  24.  
  25.  
  26. int activity_selection(int n)
  27. {
  28.     sort(&A[0], &A[n]);
  29.  
  30.     int c = 0, lastEnd = 0;
  31.  
  32.     for (int i=0; i<n; i++){
  33.  
  34.  
  35.         if (A[i].startT >= lastEnd ){
  36.  
  37.             c++;
  38.             lastEnd = A[i].endT;
  39.             printf("[%d, %d]\n", A[i].startT, A[i].endT);
  40.         }
  41.  
  42.     }
  43.  
  44.     return c;
  45.  
  46. }
  47.  
  48. int main()
  49. {
  50.     freopen("input.txt", "r", stdin);
  51.  
  52.     int n;
  53.  
  54.     scanf("%d", &n);
  55.     for(int i = 0; i < n; ++i)
  56.         scanf("%d %d", &A[i].startT,
  57.               &A[i].endT);
  58.  
  59.     printf("Input data:\n\n");
  60.     for(int i = 0; i < n; ++i)
  61.         printf("[%d, %d]\n", A[i].startT, A[i].endT);
  62.  
  63.     int c = activity_selection(n);
  64.  
  65.     printf("\nSorted Data:\n\n");
  66.     for(int i = 0; i < n; ++i)
  67.         printf("[%d, %d]\n", A[i].startT, A[i].endT);
  68.  
  69.  
  70.     printf("\nMax activities selected = %d\n", c);
  71.  
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement