Official

D - Strange Balls Editorial by en_translator


In order to determine if the balls will disappear, we have to manage how many balls with the same integer written on them.

Consider managing the consecutive balls with the same integer in the form of \((\text{integer}, \text{number})\).

Consider inserting a new ball with \(x\) written on it. If the cylinder is empty, insert \((x, 1)\) anew. If the cylinder is not empty and the topmost consecutive part is represented by \((a, b)\),

  • If \(a \neq x\), insert \((x, 1)\) anew.
  • If \(a = x\), replace \((a, b)\) with \((a, b + 1)\).
    • Here, if it becomes \(a = b + 1\), remove \((a, b + 1)\). This operation corresponds to the disappearance of the balls.

The operations above can be implemented with a data structure called stack. The stack supports the following operations:

  • \(\mathrm{push}(x) : \) Insert \(x\) anew.
  • \(\mathrm{top}() : \) Find the last element inserted that currently remains.
  • \(\mathrm{pop}() : \) Remove the last element inserted that currently remains.

It would be easier to understand intuitively by imagining stacking books on the desk and removing a book from the top.

Sample code (C++)

posted:
last update: