Activity arrangement problems (Greedy algorithms) and greedy activity Arrangement
Problem description:
There are n Activity sets E. Each activity requires the same resource, and resources can only be used by one activity at the same time, each activity has a start time and an end time. It is required to select m activities from activity set E so that m activities can proceed smoothly, that is to say, the activity time of each activity does not cross each other, and the maximum value of m and the selected activity sequence number are obtained.
For example, enter:
Activity No. 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 program uses the greedy algorithm to solve the problem. The output answer is:
The activity number to be selected is:
1 4 8 11 (up to 4 activities can be arranged)
# Include <iostream> # include <iterator> # include <vector> # include <algorithm> using namespace std;/** campaign scheduling (Greedy algorithm) */struct Act {int beg; // Activity start time int end; // activity end time int index; // activity ID: friend ostream & operator <(ostream & o, const Act & A); friend istream & operator> (istream & o, Act & );}; ostream & operator <(ostream & o, const Act & A) {o <. beg <"---" <. end <"; return o;} istream & operator> (istream & o, Act & A) {o>. index>. beg>. 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) {// sort the activity by the end time of the activity. begin (), acts. end (), cmp); // select a feasible active vector <int> res; res. push_back (acts [0]. index); // first select the first active int now = 0; // the currently selected active 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; // obtain the activity Id set res_act = GreedySelector (acts) in the scheme ); // output result copy (res_act.begin (), res_act.end (), ostream_iterator <int> (cout, ""); cout <endl ;}