Can someone provide some insight on how to approach this problem ?
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
Name |
---|
There are two ways I know how to solve a problem like this, small-to-large merging on a tree and centroid decomposition. I'll describe the centroid decomp solution here.
First, we need to note a couple of properties about balanced parentheses strings. As you probably know, if you assign each $$$($$$ to a $$$1$$$ and each $$$)$$$ to a $$$-1$$$, the total sum of the string has to equal $$$0$$$. Moreover, the min prefix sum must be $$$>= 0$$$ as well (but because the total sum is always $$$0$$$, in a balanced string the $$$min ps$$$ is always $$$0$$$). From this point forward, I'm going to refer to the "min prefix sum" as $$$min ps$$$, and the "total sum" as $$$sum$$$.
Now what happens when we concatenate two parentheses sequences? (let's denote them as strings $$$s1$$$ and $$$s2$$$). We need to check if the string $$$s1+s2$$$ is balanced. It is balanced iff, $$$s1$$$'s $$$min ps$$$ is $$$>= 0$$$, $$$s1$$$'s $$$sum + s2$$$'s $$$sum = 0$$$, and $$$s2$$$'s $$$min ps$$$ is $$$>= s2$$$'s $$$sum$$$. I'll leave the proofs as an exercise for the reader.
First, apply standard centroid decomp. Now we just need to solve for all paths going through a certain node. Calculate the $$$sum$$$ and $$$min ps$$$ for all paths leaving the current node and all paths ending at the current node. Using the property above, it is easy to check if it is possible to combine two things. Because the first and third properties are local, you can check if the current string satisfies them without even looking at any other strings. To count how many pairs satisfy the second property, you can store the paths ending at the current node in a map, keyed by the $$$sum$$$ of the string.
Let me know if anything was confusing.
EDIT: A similar problem can be found here