Editorial
Let , and let be the time when switch is operated. Record only the relative order of adjacent switches:
Two complete orders with the same sign sequence differ only by swaps of disjoint switches, so they have the same result and cost. Conversely, orienting the edges of a path never creates a directed cycle, so every sign sequence is realizable.
Add virtual signs and . For switch , define
The two original cards seen by switch started at positions and . Thus this switch costs money exactly when .
While deciding signs from left to right, an open descending run shares one future right card: the card immediately to the right of the next upward sign. Its exact position is unnecessary; only its color or matters.
Maintain four DP values:
- : no descending run is open, and the next switch's left original card has color .
- : a descending run is open, assuming its common future right card has color .
At switch , let and . Choosing an upward sign sends to with cost , and sends to with cost . Choosing a downward sign sends to each with cost , and sends to itself with cost .
Initialize . At the last real switch, allow only the upward transition to implement the virtual final sign. The answer is . The time complexity is and the extra memory excluding the input string is .
Solution written by GPT5