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
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)
.
思路:在存的时候就消掉左右括号。
注意要用longlong
代码:
#include<bits/stdc++.h>
using namespace std;
string h;
struct node
{
long long l,r;
}X[300010];
long long lala_r[300010];
long long lala_l[300010];
int main()
{
int n;
scanf("%d",&n);
memset(X,0,sizeof(X));
memset(lala_r,0,sizeof(lala_r));
memset(lala_l,0,sizeof(lala_l));
long long cnt1=0;
long long maxx=0;
for(int i=1;i<=n;i++)
{
cin>>h;
for(int j=0;j<h.length();j++){
if(h[j]=='(')
X[i].r++;
else
{
if(X[i].r>=1)
X[i].r--;
else
{
X[i].l++;
}
}
}
maxx=max(max(maxx,X[i].l),X[i].r);
///cout<<X[i].l<<"%%%%%%"<<X[i].r<<endl;
if(X[i].l==0&&X[i].r==0)
cnt1++;
else if(X[i].l!=0&&X[i].r!=0)
continue;
else{
if(X[i].l==0&&X[i].r!=0)
lala_r[X[i].r]++;
else if(X[i].r==0&&X[i].l!=0)
lala_l[X[i].l]++;
}
}
cnt1=cnt1*cnt1;
/// cout<<cnt1<<"&&&"<<endl;
for(int i=1;i<=maxx;i++)
{
if(lala_r[i]>0&&lala_l[i]>0)
cnt1=cnt1+lala_r[i]*lala_l[i];
}
cout<<cnt1<<endl;
return 0;
}