D - Greedy Balancer Editorial by evima Editorial for printing
Let \(S\) be the total weight of the stones. If \(S\) is odd, the answer is \(0\). Below, we arrange the stones in ascending order of weight as \(w_1,\ldots,w_N\).
Consider only the first \(k\) stones, with the goal of making the total weight on the red plate equal to \(t\). We move the lightest stone from the red plate if the red plate is heavier than \(t\), and from the blue plate if it is lighter.
Here, let us focus on the case where the heaviest stone \(w_k\) is on the blue plate. Let \(P\) be the total weight of the remaining stones. If \(t\le P\), the heaviest stone never moves. If \(t>P\), we reach the state where all stones are on the red plate, regardless of the initial placement. After that, if \(t\ge w_k\), we can fix the heaviest stone on the red plate and consider only the remaining stones; if \(t<w_k\), the target cannot be achieved.
From this, we consider the following DP.
- \(X[k][t]\): the number of initial placements of the first \(k\) stones for which the process ends with the weight on the red plate equal to \(t\).
- \(Y[k][t]\): \(1\) if, when starting with all of the first \(k\) stones on the blue plate, the process ends with the weight on the red plate equal to \(t\); \(0\) otherwise.
Let \(S_k=\sum_{i=1}^k w_i\). The initial values are \(X[0][0]=Y[0][0]=1\), and the values for \(t\notin[0,S_k]\) are \(0\).
When the heaviest stone is on the blue plate, we add \(X[k-1][t]\) if \(t\le S_{k-1}\). Otherwise, all initial placements converge to the state where all stones are on the red plate, so we add \(2^{k-1}Y[k-1][S_k-t]\). Here, we consider the remaining stones with red and blue swapped. When the heaviest stone is on the red plate, it suffices to add the contribution of the case where red and blue are swapped and the target is \(S_k-t\).
Also, \(Y[k][t]\) equals \(Y[k-1][t]\) if \(t\le S_{k-1}\), and \(Y[k-1][S_k-t]\) otherwise.
By computing these in ascending order of \(k\), we obtain the answer \(X[N][S/2]\). The time complexity is \(O(NS)\), which is fast enough.
posted:
last update: