Editorial for COCI '07 Contest 1 #5 Srednji


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

One obvious observation is that if the median of subsequence is B then the subsequence contains B.

For a subsequence P, we define a function \delta(P) as the difference of elements greater than B and elements smaller than B. Thus B is the median of P if and only if P contains B and \delta(P) = 0.

Furthermore, if we split P into subsequences P_L – part that is left of B and P_R – part that is right of B, then P has median B if \delta(P_L) + \delta(P_R) = 0.

This leads to the following algorithm:

For each subsequence ending with B we calculate the delta function and store the number of subsequences having delta value of d in L(d).

For each subsequence starting with B we calculate the delta function and store the number of subsequences having delta value of d in R(d).

To obtain the solution for each value d from [-N, N], we sum L(d) \times R(-d).


Comments

There are no comments at the moment.