Official

E - Pair of Sequences Editorial by evima


Let \(V\) be the upper limit of the values, that is, \(2 \times 10^5\).

Let \(M := M - 1\) and \(B\) be a subsequence of \((0, 1, 2, \ldots, M)\), and consider making the sum of \(A\) to \(X\) and the sum of \(a_i b_i\) to \(Y\). When \(N = M + 1\), that is, when \(B = (0, 1, 2, \ldots, M)\), the problem becomes counting multisets of non-negative integers with size \(X\), sum \(Y\), and maximum value at most \(M\). It is known that the answer is the coefficient of \(q^Y\) in \(\binom{M + X}{X}_q = \frac{(1 - q^{M + X})(1 - q^{M + X - 1}) \ldots (1 - q^{M + 1})}{(1 - q)(1 - q^2) \ldots (1 - q^X)}\).

Based on the above, consider the case when \(N > M + 1\). Let \(f(K)\) be the number of multisets of non-negative integers with size \(X\), sum \(Y\), maximum value at most \(M\), and containing exactly \(K\) distinct values. Then, the answer is \(\sum_{i=1}^{\min(N, M + 1)} \binom{M + 1 - i}{N - i} f(i)\). Also, since \(1 + 2 + \ldots + n = \frac{n(n + 1)}{2}\), the number of values to consider as \(K\) is \(\mathrm{O}(\sqrt{V})\). If we can find \(g(K)\), the number of multisets of non-negative integers with size \(X\), … and necessarily containing certain \(K\) values, we can also find \(f(K)\) by inclusion-exclusion.

Multisets that necessarily contain certain \(K\) values can be constructed by combining those \(K\) values each taken once and a multiset of size \(X - K\). The \(K\) values taken once can be obtained by adding \(0, 1, \ldots, K - 1\) to the elements of a multiset of size \(K\) and maximum value at most \(M - K + 1\) from smallest to largest, so we can count them by considering \(\binom{M + 1}{K}_q\). The multisets of size \(X - K\) is counted by \(\binom{X + M - K}{X - K}_q\), so \(g(K)\) is the coefficient of \(q^{Y - \frac{K(K - 1)}{2}}\) in \(h_K = \binom{M + 1}{K}_q \binom{X + M - K}{X - K}_q\).

We can compute \(h_1\) using formal power series operations by considering \(h_1' = \log h_1\), computing the product of \((1 - q^i)\) by seeing it as the sum of \(\log(1 - q^i)\), and then finding \(h_1 = \exp(h_1')\), which can be done in \(\mathrm{O}(Y \log Y)\) time. Also, if we find \(h_2, \ldots, h_K\) in order, the differences involve multiplication/division of a constant number of \((1 - q^i)\), so each computation can be done in \(\mathrm{O}(V)\) time. Recalling that the range of \(K\) is \(\mathrm{O}(\sqrt{V})\), the total computation can be done in \(\mathrm{O}(V \sqrt{V})\).

posted:
last update: