Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. struct interval { int s; int e; }
  2.  
  3. struct comparator {
  4. bool operator(const interval& i1, const interval& i2) const {
  5. int i=i1.e-i2.e; // higher ends placed last
  6. if(0==i) { // higher length/lower starts will be higher
  7. i=i2.s-i1.s;
  8. }
  9. return i<0;
  10. }
  11. }
  12.  
  13. int count_intervals(std::vector<interval>& sets) {
  14. if(sets.empty()) return 0;
  15.  
  16. comparator comp;
  17. std::sort(sets.begin(), sets.end(), comp);
  18.  
  19. /* if you need the solution as well, use a stack */
  20. // std::stack<std::vector> solution;
  21. interval& stack_top=sets[sets.size()-1]; // solution.push(stack_top);
  22. int count=1; // jave at least
  23. for(int i=sets.size()-2; i>=0; i--) {
  24. interval& curr=sets[i];
  25. if(curr.s > stack_top) { // a better one, lets more room in front
  26. stack_top=curr; // solution.pop(); solution.push(curr);
  27. }
  28. else if(curr.e < stack_top.s) {
  29. stack_top=curr; // solution.push(curr);
  30. count++;
  31. }
  32. }
  33. // if you need the solution, arrange the params of the function to return it
  34. return count;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement