yesnomaybe's blog

By yesnomaybe, history, 3 years ago, In English

Question link : https://www.codechef.com/problems/AVGMED Question summary : Find number of subarrays of length K, such that average >= median and also the median and average must both be prime or non prime.

Solution link using ordered_set : https://www.codechef.com/viewsolution/39036972 Am I doing something wrong with how to use ordered_set? Or my solution is wrong itself? Please help.

Code

Another solution : https://www.codechef.com/viewsolution/38989875 Similar solution which got accepted. I am not to able to see what I did wrong (I am blind or what?). Can someone kindly help?

  • Vote: I like it
  • +3
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Update : On changing the custom comparator function from cmp to less, the solution passed.

Custom comparator function :

template <class T> struct cmp {
	bool operator() (T x, T y) {
		return x.first < y.first;
	}
};

I am trying to create an ordered multiset, and for that using pair. I want this set to be ordered on first value. But I don't see what's wrong with my comparator function though which led to wrong answer?

Is it because there could be multiple entries with same first value but different second value, and due to that the ordered_set is not able to handle "find_by_order" correctly. But I don't see how that should be the case? As I care about order imposed only by first key of the pair.

Can someone please explain what I am missing here? And how to use ordered_set over pair<int,int> i.e ordered_multiset?

»
3 years ago, # |
  Vote: I like it +3 Vote: I do not like it

I think you've written wrong comparator for the ordered_set. I changed it to this and It worked.

You can check AC code from here.

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

    Yeah, I understand that something is wrong with my comparator function. But can you explain why the above didn't work?

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

    Yeah I see that it will work, but can you explain why we need to explicitly write condition for second value in pair? As in I only want set to be sorted as per first value, and in my comparator function if first values are equal then it will return false. As I don't care about the order of entries that have same first value.

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

      Your comparator must ensure strict weak ordering. See link. This is not limited to pbds ordered set. You can replicate similar 'bugs' with STL set.