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)
题意:给出n个只由‘( ’和‘ )’组成的字符串,判断两个字符串是否可以组成一个完美的括号匹配(这里的两个字符串组合,按样例来看,应该是将字符串i插入字符串j的任意位置。或者相反),求n个字符串中,可以组成完美括号匹配的有多少种(注意!第二和第三个匹配,与第三个和第二个匹配算两种!如果一个字符串已经是完美括号匹配了,那么它自己也算一种)
思路:求出每个字符串中,左括号和右括号多出来的个数(即,在字符串中,无法完成匹配的括号的个数,如果同时存在左括号和右括号无法完成匹配,那么,这个字符串和任意一个字符串组合都无法达成完美括号匹配!!),然后,将无法完成匹配的左括号个数和等数量的右括号个数的字符串相成,再累加即可(最后一句有点拗口,不过,看代码的话一下就可以理解了)
#include "iostream"
#include "string"
using namespace std;
typedef long long ll;
const int Max=3e5+10;
ll L[Max],R[Max];//记录如果有i个括号未匹配的字符串的个数
int main()
{
ios::sync_with_stdio(false);
int n,l,r;
ll ans=0;
string str;
cin>>n;
for(int i=0;i<n;i++){
cin>>str;
l=r=0;
for(int j=0;j<str.size();j++) {
if (str[j] == '(') l++;
else l?l--:r++;//判断在右括号之前是否有左括号,如果有,那么匹配成功,无法匹配的左括号减1。否则,无法匹配的右括号加1
}
if(r==0) L[l]++;//如果同时有左右括号未匹配,那么必定不能匹配成功,所以不记录。
if(l==0) R[r]++;
}
for (int i=0;i<=Max;++i) ans+=L[i]*R[i];//i表示个数,即无法完成匹配的括号的个数
cout<<ans<<endl;
}