code_warrior's blog

By code_warrior, history, 4 years ago, In English

Hello,friends. Recently, I was solving a problem Two Platformswhich required sorting the pairs in such a way that the elements with the smaller value of second element is sorted earlier and if the the second element of two pairs are same then the element with smaller value of first element is sorted earlier, I just want to ask what should be our comparator for this.

Wrong Answer with first compartor

Right Answer with comparator of second type

Should it be like:

bool comp(pair<ll,ll>a,pair<ll,ll>b) { return a.second<b.second; }

or

bool comp(pair<ll,ll>a,pair<ll,ll>b) { if(a.second==b.second) return a.first<b.first;

return a.second<b.second; }

Well, when i tried submitting my code with the first comparator and it gave me the wrong result but with the second one everything worked fine.Can someone explain his idea about this.

  • Vote: I like it
  • -8
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

If two pairs $$$a$$$ and $$$b$$$ have $$$a.ss = b.ss$$$ and $$$a.ff<b.ff$$$ then they your first comparator considers that $$$b<a$$$ when that isn't the case.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Can you explain more please?

    • »
      »
      »
      4 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      For example if $$$a=$$${$$$3,5$$$} and $$$b=$$${$$$4,5$$$}, your first comparator would check only if $$$a.ss<b.ss$$$. In this case, it would return false, while your second comparator would aditionally check if $$$a.ff<b.ff$$$ and would return true.