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?