#P7269. Replacing Brackets to Form a Valid Parentheses Sequence
Replacing Brackets to Form a Valid Parentheses Sequence
Replacing Brackets to Form a Valid Parentheses Sequence
You are given a string (S) of length (N) consisting of the characters '('
, ')'
and ']'
. In this string, there are (M) occurrences of ']'
and all other characters are either '('
or ')'
. You are allowed to replace each occurrence of ']'
with a positive number of closing parentheses (i.e. ')'
). Your task is to choose the number of ')'
characters for each ']'
such that after all replacements, the resulting string becomes a valid parentheses sequence.
A parentheses sequence is valid if and only if:
- In every prefix of the string, the number of
'('
is greater than or equal to the number of')'
. - The total number of
'('
equals the total number of')'
in the entire sequence.
If a valid replacement exists, output the resulting string on the first line, followed by the number of ')'
that replaced each ']'
in the order of appearance in (S). If no valid replacement exists, output a single line containing 0.
Note: All mathematical formulas are written in (\LaTeX) format.
inputFormat
The input consists of two lines:
- An integer \(N\) representing the length of the string \(S\).
- A string \(S\) of length \(N\) composed of the characters `'('`, `')'` and `']'`.
outputFormat
If a valid replacement exists:
- The first line should contain the resulting valid parentheses sequence after replacing each `']'`.
- Then, for each occurrence of `']'` in \(S\) (in order), output a line with the positive integer representing the number of closing parentheses used to replace that `']'`.
If no valid replacement exists, output a single line containing 0
.
sample
4
((])
(())
1
</p>