Official

C - Penguin Skating Editorial by evima


Let us focus on the numbers of consecutive squares without penguins. Assume that there are \(x_0,x_1,\cdots,x_N\) consecutive empty squares in the beginning. Here, \(x_0\) is the number of empty squares to the left of Penguin \(1\), \(x_N\) is that to the right of Penguin \(N\), and \(x_i\) (\(1 \leq i \leq N-1\)) is that between Penguin \(i\) and Penguin \(i+1\).

Considering the change in \(x\) caused by the operation of moving a penguin, we can see that the operation is rephrased as follows: choose \(i\) and choose \(j=i+1\) or \(i-1\), then let \(x_j+=x_i,\ x_i:=0\).

Let \(y_0,y_1,\cdots,y_N\) be the number of consecutive empty squares in the goal state. \(y_i\) must be a result of combining consecutive values in \(x_i\) and moving it. When \(y_i>0\), let us find the range \([l,r]\) from which \(y_i\) derives, and consider the cost it takes to move it to \(i\). We can see that we need at least \(\mathrm{max}(i-l,0)+\mathrm{max}(r-i,0)\) operations. We can also see that this minimum number of operations is sufficient. (We have to consider the order in which \(y_i\) are produced by gathering values. However, in the end, there is a sequence of operations that, for every \(i\), achieves the objective in the minimum number of operations needed.)

We can implement the procedure above to work in \(O(N)\) time.

posted:
last update: