1

This question has been asked before, Finding minimum number of points which covers entire set of intervals? Now the answer says the intervals are to be sorted according to end times. My question is, why is it wrong to sort according to start times instead? Here's the code I've written-

   struct Interval {
   int start;
   int end;
   };
   bool helper(Interval a,Interval b)
   {
   return a.start<b.start;
   }
   int main() { 
     int t;
     cin>>t;
     while(t--)
     {
     int n,c;
     cin>>n>>c;
     vector<Interval> i(n);
     for(int j=0;j<n;j++)
     {
        cin>>i[j].start>>i[j].end;
     }

     sort(i.begin(),i.end(),helper);
     int count=1;
     Interval s=i[0];
     for(int j=1;j<n;j++)
     {
        if(i[j].start>s.end)
        {
            count++;
            s=i[j];
        }
     }
     cout<<count*c<<endl;
   }
   return 0;
}

If I change my helper function to return a.end<=b.end I get the correct answer. (I'm using an online judge). To me, it seems that sorting by start times should give the right output too, I can't really think of an example where it doesn't. Could someone provide me with one?

1 Answers1

0

Here's the example

enter image description here

When sorting by start, the red interval is taken first. Which means that count won't increment until there's an interval whose start is greater than 10. So the output from your algorithm will be 1. But it should be 2 since the green and blue intervals don't overlap each other.

OTOH, if the algorithm sorts by end point (as described in the answer to the linked question), then green contributes point 4, blue contributes point 8, and red is already covered. Which yields the correct answer 2.

user3386109
  • 34,287
  • 7
  • 49
  • 68