Codeforces Round 819 (Div. 1 + Div. 2) and Grimoire of Code Annual Contest 2022
C
Jatayu's Balanced Bracket Sequence
Codeforces
1300
原题
← BD →
翻译中…

Last summer, Feluda gifted Lalmohan-Babu a balanced bracket sequence $s$ of length $2 n$.

翻译中…

Topshe was bored during his summer vacations, and hence he decided to draw an undirected graph of $2 n$ vertices using the balanced bracket sequence $s$. For any two distinct vertices $i$ and $j$ ($1 \le i \lt j \le 2 n$), Topshe draws an edge (undirected and unweighted) between these two nodes if and only if the subsegment $s[i \ldots j]$ forms a balanced bracket sequence.

翻译中…

Determine the number of connected components in Topshe's graph.

翻译中…

See the Notes section for definitions of the underlined terms.

翻译中…

Input

翻译中…

Each test contains multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^5$) — the number of test cases. Description of the test cases follows.

翻译中…

The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the number of opening brackets in string $s$.

翻译中…

The second line of each test case contains a string $s$ of length $2 n$ — a balanced bracket sequence consisting of $n$ opening brackets "(", and $n$ closing brackets ")".

翻译中…

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.

翻译中…

Output

翻译中…

For each test case, output a single integer — the number of connected components in Topshe's graph.

翻译中…

Note

翻译中…

Sample explanation:

翻译中…

In the first test case, the graph constructed from the bracket sequence (), is just a graph containing nodes $1$ and $2$ connected by a single edge.

翻译中…

In the second test case, the graph constructed from the bracket sequence ()(()) would be the following (containing two connected components):

翻译中…

image

翻译中…

Definition of Underlined Terms:

翻译中…
  • A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters $+$ and $1$. For example, sequences (())(), (), and (()(())) are balanced, while )(, ((), and (()))( are not.
  • The subsegment $s[l \ldots r]$ denotes the sequence $[s_l, s_{l + 1}, \ldots, s_r]$.
  • A connected component is a set of vertices $X$ such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to $X$ violates this rule.
翻译中…

样例

Input #1
4
1
()
3
()(())
3
((()))
4
(())(())
Output #1
1
2
3
3
InputCopy OutputCopy
题目信息
题号
1726C
时间限制
2 s
内存限制
256 MB
标签
数据结构
并查集
图论
贪心

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。