Official

E - Mancala 2 Editorial by en_translator


Considering the operation of putting \(N\) balls in bulk, the procedure is rephrased as follows:

  • Take out all the balls from box \(B_i\) and hold them in hand.
  • Let \(X\) be the number of balls in hand. Put \(\left\lfloor\frac{X}{N}\right\rfloor\) balls to each box.
  • Let \(X\) be the number of balls remaining in hand. Put one ball into each of box \(B_i+1\) through box \(B_i+X\).
    (If \(B_i+X\geq N\), “box \(B_i+1\) through box \(B_i+X\)” means box \(B_i+1\) through box \(N-1\), and box \(0\) through box \(B_i+X-N\).)

The operations that has to be applied on the array that represents the number of balls in each box are point update and segment addition. Using a data structure like a lazy segment tree, they can be processed in \(O(\log N)\) time each, for a total of \(O((M+N)\log N)\) time to solve the entire original problem.

posted:
last update: