Official

D - (ox) Editorial by evima


We can assume that we only swap the following pairs of characters:

  • )(
  • )o
  • )x
  • o(
  • x(

If there is an optimal solution that swaps other pairs of characters, we can transform it to get a solution that only swaps above pairs without a loss. This can be proved with just case analysis, and we will omit it here.

Let us pick up the (s and )s in \(S\) and focus on them. The string obtained this way must also be balanced. If we are to make this string balanced with the minimum cost, the final state of the string will be unique. Let \(T\) be this final state. We can see that, for any optimal solution for the original string, picking up the (s and )s in the final state will result in a string equal to \(T\). This follows from the fact that a valid solution after removing “unnecessary” swaps of )( is still valid.

Now, let us first think of operations so that (s and )s are balanced when the other characters are ignored. Here, the final state has some degrees of freedom on the relative positions of (s and )s compared to os and xs.

For example, in the case )ox(, we can choose to make it ox() or ()ox. In general, we can sum it up as follows.

Let us call a position a “valley” where the numbers of (s and )s so far are equal when seen from the beginning from \(T\). Also, for each o and x, let its height be (the number of (s to the left of it) - (the number of )s to the left of it). Let us ignore the os and xs whose heights are \(1\) or above already in the beginning. Then, for each o and each x, there is an interval \([l,r]\) such that the character will be at the \(l\)-th, \((l+1)\)-th, \(\cdots\), or \(r\)-th valley in \(T\). Also, since an o or x will never be swapped with another o or x, the relative positions of these characters must be maintained. Furthermore, from the fact that a swap involving an o or x always increases its height by \(1\) and the fact that the heights of those characters will be eventually \(0\), the total number of swaps is constant.

For example, when \(S=\))x)o(x(, \(T=\)()() and we have three valleys. Each of these o and xs will be at one of the positions indicated by the stars below.

  • The first x: ☆()☆()
  • o: ☆()☆()☆
  • The last x: ()☆()☆

Now, consider a part in the form ) \(+(\) a sequence of os and xs \()+\)(. To make the height of the middle \(x\) \(1\) or above, we need to move the ) and ( at both ends. It can be interpreted that the consecutive os in the middle part decrease the cost.

Now, we can use DP to solve the problem, by letting \(dp[i][j]\) as the minimum cost until the \(i\)-th valley when up to the \(j\)-th of the os and xs are used. For the first and last valleys, however, we need to take care of the cost, which will be slightly different from in other cases. This DP works in \(O(|S|^2)\) time, which is fast enough.

posted:
last update: