DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

One-Use Switch

Back to problem

Editorial

Let M=N−1M=N-1M=N−1, and let TiT_iTi​ be the time when switch iii is operated. Record only the relative order of adjacent switches:

εi={↑,Ti<Ti+1,↓,Ti>Ti+1.\varepsilon_i= \begin{cases} \uparrow,&T_i<T_{i+1},\\ \downarrow,&T_i>T_{i+1}. \end{cases}εi​={

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 ε0=↓\varepsilon_0=\downarrowε0​=↓ and εM=↑\varepsilon_M=\uparrowεM​=↑. For switch iii, define

pi=max⁡{j<i:εj=↓},qi=min⁡{j≥i:εj=↑}.p_i=\max\{j<i:\varepsilon_j=\downarrow\},\qquad q_i=\min\{j\geq i:\varepsilon_j=\uparrow\}.pi​=max{j<i:ε

The two original cards seen by switch iii started at positions pi+1p_i+1pi​+1 and qi+1q_i+1qi​. 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 000 or 111 matters.

Maintain four DP values:

  • UcU_cUc​: no descending run is open, and the next switch's left original card has color ccc.
  • DzD_zDz​: a descending run is open, assuming its common future right card has color .

At switch iii, let a=Sia=S_ia=Si​ and b=Si+1b=S_{i+1}b=S. 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 US1=0U_{S_1}=0US1​​=0. At the last real switch, allow only the upward transition to implement the virtual final sign. The answer is min⁡(U0,U1)\min(U_0,U_1)min(U. The time complexity is and the extra memory excluding the input string is .

Solution written by GPT5

↑
,
↓,
​
Ti​<Ti+1​,Ti​>Ti+1​.​
j
​
=↓
},qi​=
min{j≥
i:
εj​=↑
}.
+
1
Spi+1XORSqi+1=1S_{p_i+1}\mathbin{\mathrm{XOR}}S_{q_i+1}=1Spi​+1​XORSqi​+1​=1
zz
z
i+1
​
UcU_cUc​
UcU_cUc​
Ci[c≠b]C_i[c\neq b]Ci​[c=b]
DbD_bDb​
UaU_aUa​
Ci[a≠b]C_i[a\neq b]Ci​[a=b]
UcU_cUc​
DzD_zDz​
Ci[c≠z]C_i[c\neq z]Ci​[c=z]
DzD_zDz​
Ci[a≠z]C_i[a\neq z]Ci​[a=z]
0​
,
U1​
)
O(N)O(N)O(N)
O(1)O(1)O(1)