Can someone provide some insight on how to approach this problem ?
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 153 |
Название |
---|
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