Problem Description:
There are n activity set E, each of which requires the use of the same resource, and at the same time the resource can only be used by one activity, each activity has a start is the time and end time, the request from the activity set E to select M activities, so that the M activities can be carried out smoothly, That is, the active time of each activity does not intersect each other, seeking the maximum value of M and the selected activity sequence number.
For example, enter:
Activity number activity Start time activity end time
1 1 4
2 3 5
3 0 6
4 5 7
5 3 8
6 5 9
7 6 10
8 8 11
9 8 12
10 2 13
11 12 14
This procedure uses the greedy algorithm solves, the output answer is:
The activity number that should be selected is:
1 4 8 11 (that is, the maximum number of these 4 activities can be arranged)
#include <iostream> #include <iterator> #include <vector> #include <algorithm>using namespace std;/** activity scheduling problem (greedy algorithm) */struct act{int beg;//activity start time int end;//activity end time int index;//activity number friend Ostream & operator< < (ostream &o,const Act &a); Friend IStream & Operator>> (IStream &o, Act &a);};o Stream & operator<< (ostream &o,const Act &a) {o<<a.beg<< "---" <<A.end<< ""; return o;} IStream & Operator>> (IStream &o, Act &a) {O>>a.index>>a.beg>>a.end;return o;} BOOL CMP (ACT & act1,act & Act2) {if (act1.end<act2.end) {return true;} Else{return false;}} Vector<int> Greedyselector (vector<act> & Acts) {//First sort the activity by the end time of the activity sort (acts.begin (), Acts.end (), CMP);//Select a viable activity in the sorted activity set vector<int> res;res.push_back (Acts[0].index);//Select first Active int now = 0;//the currently selected activity subscript for ( int i = 1; I < acts.size (); i++) {if (acts[i].beg>=acts[now].end) {now = I;res.push_back (Acts[i].index);}} return res;} int main () {vector<act> acts;//optional Activity Set Copy (Istream_iterator<act> (CIN),istream_iterator<act> (), Back_inserter (Acts));cout<<endl;vector<int> res_act;//The activity number set in the scheme is Res_act = greedyselector (Acts);// Output copy (Res_act.begin (), Res_act.end (),ostream_iterator<int> (cout, "")); Cout<<endl;}
Activity scheduling problem (greedy algorithm)