Thursday, 20 April 2017

BUSYMAN - I AM VERY BUSY

EXPLANATION:

you are given set of 'n' activities with their time slot  and between that time slot only that activity can be done. 
So basically what we can do is :
 1. first we will sort all the activities according to their ending time in ascending order.
 2.than we will start selecting activity according to their to ending time and starting time.

So after sorting we will declare some 'prevend' variable and initialised to -1 or any other negative value , this variable will store the ending time of previously selected activity.
And declare a variable 'ans' which is initialised  to 0 , this will store the number of activities that can be done.

if(the starting time of next activity is greater than or equal to previous ending time )
  then 
   {      
             prevend is updated with ending time of selected activity and
             increment the number of activity that can be done by 1
   }

NOTE:sorting of array or vector of pair first compare the first element if they are same than second  element is considered.



SOLUTION:

USING VECTOR AND PAIR (STL)[C++]

#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<pair<int,int> > SCHEDULE;
vector<pair<int,int> > ::iterator itr;
int t,n,i,a,b,ans,prevend;
cin>>t;
while(t--)
{
cin>>n;
for(i=0;i<n;i++)
{
cin>>a>>b;
SCHEDULE.push_back(make_pair(b,a));
}
sort(SCHEDULE.begin(),SCHEDULE.end());
/*for(itr=SCHEDULE.begin();itr!=SCHEDULE.end();itr++)
{
cout<<itr->first<<" "<<itr->second<<endl;
}*/
ans=0;
prevend=-1;
for(itr=SCHEDULE.begin();itr!=SCHEDULE.end();itr++)
if(itr->second>=prevend)
{
ans++;
prevend=itr->first;
}
cout<<ans<<endl;
SCHEDULE.clear();
}
return 0;
}

USING ARRAY AND PAIR (STL)[C++]

#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t,n,i,a,b,ans,prevend;
cin>>t;
while(t--)
{
cin>>n;
pair<int,int> SCHEDULE[n];
for(i=0;i<n;i++)
{
cin>>a>>b;
SCHEDULE[i]=make_pair(b,a);
}
sort(SCHEDULE,SCHEDULE+n);
ans=0;
prevend=-1;
for(i=0;i<n;i++)
if(SCHEDULE[i].second>=prevend)
{
ans++;
prevend=SCHEDULE[i].first;
}
cout<<ans<<endl;
}
return 0;
}



No comments:

Post a Comment

KGSS - Maximum Sum EXPLANATION: we are going to use segment tree for this because the time complexity of update and query in segment...