H - Heavy Buckets Editorial by spheniscine


We could use a technique called binary jumping / binary lifting. Let \(f_k(i)\) and \(g_k(i)\) represent “the person a bucket would end up with” and “the amount of water added to that bucket” respectively, if the bucket started at person \(i\) and then \(2^k\) operations elapsed. These can be precomputed as follows:

\[f_0(i) = A_i, \quad f_{k+1}(i) = f_k(f_k(i))\]

\[g_0(i) = i, \quad g_{k+1}(i) = g_k(i) + g_k(f_k(i))\]

Precompute these for \(0 \leq k \leq 29\). For each query, you can decompose \(T_i\) into a sum of powers of \(2\) via its binary representation, and thus use the precomputed \(f\) and \(g\) to calculate the answer in \(O(\log T_i)\).

Thus the problem is solved in \(O((N+Q) \log \max_i T_i)\).

posted:
last update: