E - Packing Potatoes Editorial by spheniscine


Define the class of the \(i\)-th potato as \((i - 1) \text{ mod } N\). Let \(f\) be a function that says “if the first potato packed in a box is of class \(x\), \(f(x)\) potatoes would be packed in it”. This can be precalculated for \(0 \le x < n\) by first noting that you would always first cycle \(\displaystyle\left\lfloor\small\frac{X}{\sum_i W_i}\right\rfloor\) times, then pack some remainder between \(0\) and \(n\) potatoes inclusive. The remainder can be found with two pointers or with prefix sum and binary search.

Let \(g\) be a function that says “if the first potato put into the current box is class \(x\), the first potato put in the next box is class \(g(x)\)”. \(g\) is related to \(f\) via \(g(x) = (x + f(x)) \text { mod } N\).

Let \(g^y(x)\) denote “the function \(g\) applied to \(x\), \(y\) times”, e.g. \(g^3(x) = g(g(g(x)))\), and \(g^0(x) = x\). The answer of query \(i\) becomes \(f(g^{K_i - 1}(0))\)

To quickly calculate \(g^y(x)\) we could use binary lifting technique: first define \(h_k(x) = g^{2^k}(x)\), and precalculate via \(h_0(x) = g(x)\) and \(h_k(x) = h_{k-1}(h_{k-1}(x))\). We can then find \(g^y(x)\) by decomposing \(y\) to a sum of powers of \(2\) (via binary representation), then applying the corresponding functions from \(h\), e.g. since \(11 = 2^3 + 2^1 + 2^0\), \(g^{11}(x) = g^{2^3}(g^{2^1}(g^{2^0}(x))) = h_3(h_1(h_0(x)))\).

Time complexity: \(O((N + Q) \log (\max_i K_i))\), space: \(O(N \log (\max_i K_i))\)

posted:
last update: