公式
E - Odd Inversion 解説 by evima 印刷ページ
Among those satisfying $1 \leq B_i \leq A_i$, let $C$ and $D$ be the numbers of those whose inversion numbers are even and odd, respectively. The value we want is $D$.
$C + D$ is simply the product of all $A_i$. Thus, it suffices to find $C - D$.
In particular, let $X_i$ be $C - D$ when the input is restricted to the first $i$ terms. We have $X_0 = 1, X_1 = A_1$, and what we want is $X_N$.
Here, for $i \geq 2$, $X_i = (A_i - A_{i - 1}) X_{i - 1} + A_{i - 1} X_{i - 2}$ holds.
- For those with $B_{i - 1} = B_i$, the parity of the inversion number of $B$ does not change even if $B_{i - 1}, B_i$ are removed. Since there are $A_{i - 1}$ possible $(B_{i - 1}, B_i)$ with $B_{i - 1} = B_i$, the contribution is $A_{i - 1}X_{i - 2}$.
- For those with $B_{i - 1} \neq B_i$, if $\max(B_{i - 1}, B_i) \leq A_{i - 1}$, then the sequence with $B_{i - 1}, B_i$ swapped can also be taken, and these two sequences include one with an even inversion number and one with an odd inversion number, so they cancel each other out. Thus, the part with $\max(B_{i - 1}, B_i) > A_{i - 1}$, that is, $B_i > A_{i - 1}$, remains, and since $B_i$ is the maximum of $B_1, B_2, \cdots, B_i$, the parity of the inversion number of $B$ does not change even if $B_i$ is removed. Since there are $A_i - A_{i - 1}$ such $B_i$, the contribution is $(A_i - A_{i - 1}) X_{i - 1}$.
Following this, $X_N$ can be computed in $O(N)$. Thus, the problem can be solved in $O(N)$ overall.
投稿日時:
最終更新: