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 δ(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 δ(P)=0.

Furthermore, if we split P into subsequences PL – part that is left of B and PR – part that is right of B, then P has median B if δ(PL)+δ(PR)=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)×R(d).


Comments

There are no comments at the moment.