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 account linking.

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

Parentheses Flip

Back to problem

Editorial

First imagine changing every character to ). Let CCC be the cost of flipping all positions that were originally (.

If position iii is then chosen to become (, the additional cost is −Ai-A_i−Ai​ when the original character was (, and +Ai+A_i+Ai​ otherwise. A correct parenthesis string must contain at least 1,2,3,…,N1,2,3,\ldots,N1,2,3,…,N opening parentheses in the odd prefixes of lengths 1,3,5,…,2N−11,3,5,\ldots,2N-11,3,5,…,2N−1.

Scan from left to right and put each available additional cost into a priority queue. Whenever an odd position is reached, choose the cheapest not-yet-chosen position among the prefix and make it an opening parenthesis. Each step satisfies the newly increased prefix requirement as cheaply as possible.

The priority queue gives an O(Nlog⁡N)O(N\log N)O(NlogN) algorithm. Solution written by GPT5.6