#P15236. [NHSPC 2025] 括號問題
[NHSPC 2025] 括號問題
Problem Description
There are many kinds of brackets, such as curly braces {}, square brackets [], and parentheses ().
In this problem, we only consider parentheses. Brackets are usually used in pairs. If a sequence made of brackets has a nested structure (nested structure), we call this sequence “well-formed”.
For example:
- Sequence
()(())is well-formed. - Sequence
(()()is not well-formed, because there is no way to make every left parenthesis match with a right parenthesis after it, while also ensuring that each right parenthesis)is matched at most once.
More formally, “well-formed” is defined as follows:
A bracket sequence is well-formed if and only if it satisfies both conditions below:
- Scanning from left to right from to , at any position during the process, the number of right parentheses
)never exceeds the number of left parentheses(. - The total number of left parentheses equals the total number of right parentheses in the sequence.
PorgramText is a software company developing a brand-new text editor for programmers. This editor will provide many powerful features, one of which is automatically fixing input mistakes.
After observing users’ typing behavior, PorgramText found that many programmers, due to typing too fast, often accidentally type extra left parentheses or right parentheses. To solve this, the editor will provide a feature: automatically convert a possibly “not well-formed” bracket sequence into a “well-formed” sequence . During the conversion, the only allowed operation is deleting left parentheses or right parentheses.
PorgramText wants you to help them: compute the minimum number of parentheses that must be deleted to turn into a “well-formed” sequence.
Input Format
$$\begin{aligned} & n \\ & P_1P_2\cdots P_n \\ \end{aligned}$$- is the length of the bracket sequence.
- is a bracket sequence consisting of
(and).
Output Format
- is the minimum number of parentheses that need to be deleted.
6
()(())
0
5
(()()
1
3
)((
3
Hint
Constraints
- .
- contains only
(and).
Scoring
This problem has three subtasks, with the constraints as follows. Each subtask may contain one or more pieces of testdata. You will receive the score for a subtask only if all testdata in that subtask are answered correctly.
| Subtask | Score | Additional Input Constraints |
|---|---|---|
| 1 | 30 | All left parentheses appear before all right parentheses (so ( and ) do not interleave). |
| 2 | can only be or . (Note: you only need to determine whether is “well-formed”.) | |
| 3 | 40 | No additional constraints. |
Translated by ChatGPT 5