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 接下来输入n行 ()
问可以组成多少种合法的括号,就是 (()(())) 这样子都算合法
解题思路:
每次取值
( 为1
) 为-1
记录相同总和的个数
答案是 sum(x * -x)的个数 就好了
注意要用long long
代码:
#include <bits/stdc++.h> using namespace std; map<long long,long long>m; int main() { int n; cin >> n; string s; for(int i=0;i<n;i++) { long long num=0; cin >> s; for(int j=0;j<s.size();j++) { if(s[j]=='(') num++; else num--; } if(num > 0) { int cnt=0; int flag=1; for(int j=0;j<s.size();j++) { if(s[j]=='(') cnt++; else cnt--; if(cnt<0) // 避免)))))( 这种情况 { flag=0; break; } } if(flag==0) { continue; } } else if(num <= 0) { int cnt=0; int flag=1; for(int j=s.size()-1;j>=0;j--) { if(s[j]=='(') cnt++; else cnt--; if(cnt>0) // 避免 (((((()这种情况 { flag=0; break; } } if(flag==0) { continue; } } m[num]++; } long long ans=0; map<long long,long long>::iterator iter; for(iter=m.begin();iter!=m.end();iter++) { if(iter->first == 0) ans+= iter->second * iter->second; if(iter->first > 0) { ans+= iter->second * m[-(iter->first)]; } } cout << ans << endl; }