E - More Peaks More Fun Editorial by evima
Let us asssume \(A_i<B_i\) and \(B_i < B_{i+1}\) without loss of generality. Then, after rearranging the condition for the sequence of boxes \(p_1,\ldots,p_N\), we can see that it is equivalent to satisfying one of the following:
- \(B_{p_i} > A_{p_{i+1}}\) for every \(1 \leq i < N\);
- \(B_{p_i} < A_{p_{i+1}}\) for some \(i\), \(B_{p_j} > A_{p_{j+1}}\) for \(1 \leq j < i\), and \(A_{p_j} < B_{p_{j+1}}\) for \(i < j < N\).
For each box \(i\), let \(U_i\) be the number of \(i\) such that \(j>i\) and \(A_j<B_i\). Then, we can see that the number of sequences satisfying the former condition is \(\prod_{1 \leq i \leq N} (U_i+1)\) by inserting the boxing in descending order of ID number. Next, let us count the sequences satisfying the latter condition.
We will fix \((b,a)\) such that \(B_b < A_a\) and count \(p\) satisfying the latter condition such that \((p_i, p_{i+1}) = (b,a)\) for some \(i\). We can see that this count is \(\prod_{1 \leq i < b} U_i \times \prod_{b<i<a} (U_i+1) \times \prod_{a< i \leq N} (U_i+2)\) by again inserting the boxing in descending order of ID number. We can solve the problem by finding this value for every \((b,a)\), which can be done in linear time using prefix sums.
posted:
last update: