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).
题意:括号匹配,选两个串,使括号匹配。水题
#include <bits/stdc++.h>
using namespace std;
const int maxn = 300005;
int n, k, tmp, tot;
long long a[maxn],b[maxn];
char str[maxn];
int main()
{
scanf("%d",&n);
int maxl = 0;
for (int i=0; i<n; i++){
scanf("%s",str);
int l = strlen(str);
maxl = max(l,maxl);
int flag = 0;
int rec = 0;
for (int j=0; j<l; j++){
if (str[j] == ')')
rec--;
if (str[j] == '(')
rec++;
flag = min(flag,rec);
}
if (flag < 0 && rec > flag)
continue;
if (flag < 0)
b[abs(flag)]++;
else
a[rec]++;
}
long long ans = 0;
for (int i=1; i<=maxl; i++){
ans += a[i]*b[i];
}
ans += a[0] * a[0];
cout<<ans<<endl;
return 0;
}