Created
May 11, 2014 01:35
-
-
Save sundeepblue/e2b50e172738e6a962c3 to your computer and use it in GitHub Desktop.
greedy, schedule movie problem, activity selection problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| http://www.geeksforgeeks.org/greedy-algorithms-set-1-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. | |
| 1) Sort the activities according to their finishing time | |
| 2) Select the first activity from the sorted array and print it. | |
| 3) Do following for remaining activities in the sorted array. | |
| …….a) If the start time of this activity is greater than the finish time of previously selected activity then select this activity and print it. | |
| */ | |
| struct movie { | |
| int start, end; | |
| movie(int s, int e) : start(s), end(e) {} | |
| }; | |
| vector<movie> select_activities(vector<movie>& movies) { | |
| vector<movie> res; | |
| if(movies.empty()) return res; | |
| sort(movies.begin(), movies.end(), [](const movie& m1, const movie& m2) {return m1.end < m2.end; } ); | |
| for(int i=0; i<movies.size(); i++) { | |
| if(i == 0) res.push_back(movies[i]); | |
| else { | |
| movie tail = res.back(); | |
| if(tail.end <= movies[i].start) // <= not < | |
| res.push_back(movies[i]); | |
| } | |
| } | |
| return res; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment