Editorial for Baltic OI '12 P1 - Brackets
Submitting an official solution before solving the problem yourself is a bannable offence.
Let's define a correct string of parentheses (round brackets):
()
is a correct string of parentheses;- If
A
is a correct string of parentheses, then(A)
also is a correct string of parentheses; - If both,
A
andB
, are correct parentheses strings, then the concatenationAB
is also a correct string of brackets.
In other words, a correct parentheses string is a correct string of brackets, but containing no square brackets.
Let us take an arbitrary correct string of parentheses and replace some (perhaps all, but at least one) of the closing (right) parentheses with the opening (left) parentheses. We shall name the resulting string a broken string of parentheses.
It is easy to see that every broken string of brackets is also a broken string of parentheses, and vice versa. In fact, both of them fulfil the following two conditions:
- the number of opening brackets is greater than the number of closing brackets;
- the number of opening brackets is not less than the number of closing brackets for every prefix of the string.
Accordingly, we will name both, the broken string of brackets and the broken strings of parentheses, broken strings.
For further explanation, let
Lemma
For any broken string
Proof
Let
- Let
be an arbitrary correct string of brackets from . Substitute its every square bracket with a corresponding round bracket (opening with opening, closing with closing). As a result we obtain some correct string of parentheses that matches . - Let
be an arbitrary correct string of parentheses from . We mark all closing round brackets of that correspond to closing round brackets in (that appear at the same position in and ). Then we mark all opening round brackets in that correspond to the already marked closing round brackets. Finally, we substitute all unmarked round brackets in with square brackets (opening with opening, closing with closing). As a result we obtain some correct string of brackets that matches .
It follows from (1) and (2) that
Thus, we have reduced the task to the following: calculate the number of distinct correct strings of parentheses that correspond to the given broken string. This task is solved using standard dynamic programming.
Let
, for all- If
)
then for all , . - If
(
then , for all ,
Note:
This directly leads to a solution with
Firstly, we have to avoid using a two-dimensional array; we have to somehow
obtain the same result by a manipulation of one-dimensional arrays. Note that to
calculate
Secondly, straight forward implementation of the algorithm is a bit too slow.
The correct solution is still
Note that if
The overall time complexity is
Side note: This task was proposed for IOI 2011.
Comments