C.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 nn bracket sequences s1,s2,…,sns1,s2,…,sn. Calculate the number of pairs i,j(1≤i,j≤n)i,j(1≤i,j≤n) such that the bracket sequence si+sjsi+sj is a regular bracket sequence. Operation ++ means concatenation i.e. "()(" + ")()" = "()()()".
If si+sjsi+sj and sj+sisj+si are regular bracket sequences and i≠ji≠j, then both pairs (i,j)(i,j) and (j,i)(j,i) must be counted in the answer. Also, if si+sisi+si is a regular bracket sequence, the pair (i,i)(i,i) must be counted in the answer.
The first line contains one integer n(1≤n≤3⋅105)n(1≤n≤3⋅105) — the number of bracket sequences. The following nn lines contain bracket sequences — non-empty strings consisting only of characters "(" and ")". The sum of lengths of all bracket sequences does not exceed 3⋅1053⋅105.
In the single line print a single integer — the number of pairs i,j(1≤i,j≤n)i,j(1≤i,j≤n) such that the bracket sequence si+sjsi+sj is a regular bracket sequence.
3
)
()
(
2
2
()
()
4
In the first example, suitable pairs are (3,1)(3,1) and (2,2)(2,2).
In the second example, any pair is suitable, namely (1,1),(1,2),(2,1),(2,2)(1,1),(1,2),(2,1),(2,2).
先预处理剩余的左括号和右括号,再用pair和map存,如果剩余的左括号和右括号都不会为零,那么这个串必然不能和其他串组成合法串。最后枚举剩余左括号的,看有多少个对应的右括号,这样不会重。
#include <bits/stdc++.h> #define maxn 300005 using namespace std; string a[maxn]; typedef long long ll; int lefts[maxn]={0}; int rights[maxn]={0}; bool vis[maxn]={0}; map<pair<int,int>,int> mp; int main() { int n,j,i; cin>>n; for(i=0;i<n;i++) { cin>>a[i]; } for(i=0;i<n;i++) { int l=0,r=0; for(j=0;j<a[i].size();j++) { if(a[i][j]=='(') { l++; } else if(a[i][j]==')'&&l>0) { l--; } else if(a[i][j]==')'&&l==0) { r++; } } lefts[i]=l; rights[i]=r; } for(i=0;i<n;i++) { if(lefts[i]!=0&&rights[i]!=0) { vis[i]=true; } } for(i=0;i<n;i++) { if(!vis[i]) { mp[make_pair(lefts[i],rights[i])]++; } } ll ans=0; for(i=0;i<n;i++) { if(!vis[i]&&rights[i]==0) { ans+=(ll)mp[make_pair(0,lefts[i])]; } } cout<<ans<<endl; return 0; }