Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct interval { int s; int e; }
- struct comparator {
- bool operator(const interval& i1, const interval& i2) const {
- int i=i1.e-i2.e; // higher ends placed last
- if(0==i) { // higher length/lower starts will be higher
- i=i2.s-i1.s;
- }
- return i<0;
- }
- }
- int count_intervals(std::vector<interval>& sets) {
- if(sets.empty()) return 0;
- comparator comp;
- std::sort(sets.begin(), sets.end(), comp);
- /* if you need the solution as well, use a stack */
- // std::stack<std::vector> solution;
- interval& stack_top=sets[sets.size()-1]; // solution.push(stack_top);
- int count=1; // jave at least
- for(int i=sets.size()-2; i>=0; i--) {
- interval& curr=sets[i];
- if(curr.s > stack_top) { // a better one, lets more room in front
- stack_top=curr; // solution.pop(); solution.push(curr);
- }
- else if(curr.e < stack_top.s) {
- stack_top=curr; // solution.push(curr);
- count++;
- }
- }
- // if you need the solution, arrange the params of the function to return it
- return count;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement