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(1≤i,j≤n) 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 i≠j, 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.
The first line contains one integer n(1≤n≤3⋅105)
.
In the single line print a single integer — the number of pairs i,j(1≤i,j≤n)
is a regular bracket sequence.
3 ) () (
2
2 () ()
4
In the first example, suitable pairs are (3,1)
.
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;
}