markyrocks

attending workshops hackerrank

Apr 30th, 2022 (edited)
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. //Define the structs Workshops and Available_Workshops.
  6. //Implement the functions initialize and CalculateMaxWorkshops
  7. struct Workshops{
  8.     int start_time,duration,end_time;
  9. };
  10.  
  11. struct Available_Workshops{
  12.     int n;
  13.     Workshops* ptr;
  14.  
  15. };
  16.  
  17. Available_Workshops* initialize (int start_time[], int duration[], int n){
  18.     Available_Workshops* aw=new Available_Workshops[1];
  19.         aw->ptr=new Workshops[n]{};
  20.         aw->n=n;
  21.         for(int i=0;i<n;i++){
  22.             aw->ptr[i].start_time=start_time[i];
  23.             aw->ptr[i].duration=duration[i];
  24.             aw->ptr[i].end_time=start_time[i]+duration[i];
  25.         }
  26.         return aw;
  27.     }
  28.    
  29. bool overlap(const Workshops& a, const Workshops& b){
  30.     if(b.start_time>=a.start_time && b.start_time<a.end_time){
  31.         return true;
  32.     }
  33.     else if(a.start_time>=b.start_time && a.start_time<b.end_time){
  34.         return true;
  35.     }
  36.     return 0;
  37. }
  38. int cmp(const void* a, const void* b){
  39.     Workshops* aa=(Workshops*)a;
  40.     Workshops* bb=(Workshops*)b;
  41.     if(overlap(*aa, *bb)){
  42.         return aa->end_time-bb->end_time;
  43.     }
  44.     return aa->start_time-bb->start_time;
  45.    
  46. }
  47.  
  48. int CalculateMaxWorkshops(Available_Workshops* ptr){
  49.    
  50.    qsort(ptr->ptr,ptr->n,sizeof(Workshops),cmp);
  51.    
  52.   // int s=0;
  53.    int e=0;
  54.    int c=0;
  55.    for(int i=0;i<ptr->n;i++){
  56.       if(!i){
  57.           e=ptr->ptr[i].end_time;
  58.           c++;
  59.       }
  60.       else if(ptr->ptr[i].start_time>=e){
  61.           e=ptr->ptr[i].end_time;
  62.           c++;
  63.       }
  64.    }
  65.    
  66.    
  67.     return c;
  68. }
  69.  
  70. //locked below this point
  71.  
  72. int main(int argc, char *argv[]) {
  73.     int n; // number of workshops
  74.     cin >> n;
  75.     // create arrays of unknown size n
  76.     int* start_time = new int[n];
  77.     int* duration = new int[n];
  78.  
  79.     for(int i=0; i < n; i++){
  80.         cin >> start_time[i];
  81.     }
  82.     for(int i = 0; i < n; i++){
  83.         cin >> duration[i];
  84.     }
  85.  
  86.     Available_Workshops * ptr;
  87.     ptr = initialize(start_time,duration, n);
  88.     cout << CalculateMaxWorkshops(ptr) << endl;
  89.     return 0;
  90. }
  91.  
Add Comment
Please, Sign In to add comment