cf819C Jatayu‘s Balanced Bracket Sequence

原题链接

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

Topshe was bored during his summer vacations, and hence he decided to draw an undirected graph of 2n vertices using the balanced bracket sequence s. For any two distinct vertices i and j (1≤i<j≤2n), Topshe draws an edge (undirected and unweighted) between these two nodes if and only if the subsegment s[i…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≤t≤105) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer n (1≤n≤105) — the number of opening brackets in string s.
The second line of each test case contains a string s of length 2n — 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 105.

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

Example
input
4
1
()
3
()(())
3
((()))
4
(())(())
output
1
2
3
3

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):
请添加图片描述

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…r] denotes the sequence [sl,sl+1,…,sr].
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.

思路:这个题是个假题,不涉及什么算法,找规律就可以了,可惜当时居然没写出来。
Accode:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
    
    
	ios::sync_with_stdio(false);
	cin.tie(0);
	int tt;
	cin>>tt;
	while(tt--) {
    
    
		int n;
		cin>>n;
		string s;
		cin>>s;
		int ans=n+1;
		for(int i=0; i<2*n-1; i++) {
    
    
			if(s[i]=='('&&s[i+1]==')') {
    
    
				ans--;//每次找到当前点和后继点是一对括号序列答案减一;
			}
		}
		cout<<ans<<'\n';
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Stephen_Curry___/article/details/126753709