990C. Bracket Sequences Concatenation Problem(思维+括号匹配问题)

A bracket sequence is a string containing only characters "(" and ")".

A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.

You are given n

bracket sequences s1,s2,,sn. Calculate the number of pairs i,j(1i,jn) such that the bracket sequence si+sj is a regular bracket sequence. Operation +

means concatenation i.e. "()(" + ")()" = "()()()".

If si+sj

and sj+si are regular bracket sequences and ij, then both pairs (i,j) and (j,i) must be counted in the answer. Also, if si+si is a regular bracket sequence, the pair (i,i)

must be counted in the answer.

Input

The first line contains one integer n(1n3105)

— the number of bracket sequences. The following n lines contain bracket sequences — non-empty strings consisting only of characters "(" and ")". The sum of lengths of all bracket sequences does not exceed 3105

.

Output

In the single line print a single integer — the number of pairs i,j(1i,jn)

such that the bracket sequence si+sj

is a regular bracket sequence.

Examples
Input
Copy
3
)
()
(
Output
Copy
2
Input
Copy
2
()
()
Output
Copy
4
Note

In the first example, suitable pairs are (3,1)

and (2,2)

.

In the second example, any pair is suitable, namely (1,1),(1,2),(2,1),(2,2)

.

题意:有n个字符串,每个字符串只由‘’(‘’,‘’)‘’构成,从n个字符串中任意选两个a和b,如果ab构成的字符串括号完全匹配,则结果+1,也可以是aa,ba结构,求最后的结果

思路:括号匹配问题

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 3e5+5;
string str[N];
int vis[N];
int solve(string s){
	int x=0;
	for(int i=0;i<s.length();i++){
		if(s[i]=='(') x++;
		else x--;
		if(x<0) return -1;
	}
	return x;
}
string rev(string s){
	reverse(s.begin(),s.end());
	for(int i=0;i<s.length();i++){
		if(s[i]=='(') s[i]=')';
		else s[i]='(';
	}
	return s;
}
int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>str[i];
		int x=solve(str[i]);
		if(x!=-1) vis[x]++;
	}
	LL ans=0;
	for(int i=0;i<n;i++){
		str[i]=rev(str[i]);
		int x=solve(str[i]);
		if(x!=-1) ans+=vis[x];
	}
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/islittlehappy/article/details/81012113