Latest

6/recent/ticker-posts

Activity selection problem


You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.

 

CODE:


#include <bits/stdc++.h>
using namespace std;

int main()
{
     int n;
     cin>>n;
     int start[n],ending[n];
     for(int i=0;i<n;i++)
      {
          cin>>start[i];
          cin>>ending[i];
      }
      //to sort the elements in terms of ending time
      priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;
	for(int i=0;i<n;i++)
	{
   		 pq.push(make_pair(ending[i],start[i]));
	}

	//to track the count of activities selected

	int c=0;

	//to store the activities selected

	vector<int>v1,v2;
	int p=pq.top().first;
	int q=pq.top().second;
	pq.pop();
	c++;
	v1.push_back(q);
	v2.push_back(p);
	while(!pq.empty())
	{
		if(pq.top().second>=p)
   		{

          c++;  
          p=pq.top().first;        
          q=pq.top().second;
          v1.push_back(q);
          v2.push_back(p);
    	}
   		pq.pop;
	}

	cout<<"Total no. of activities selected   "<<c<<endl;
	cout<<"The start time and end time of the activities are"<<endl;
	for(int i=0;i<v1.size();i++)
	{
    	cout<<"( "<<v1[i]<<" , "<<v2[i]<<" )"<<endl;

	}
}
OUTPUT:



Post a Comment

0 Comments