C. Bracket Sequences Concatenation Problem
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 

If (i,i) must be counted in the answer.

Input

The first line contains one integer 3⋅105.

Output

In the single line print a single integer — the number of pairs si+sj is a regular bracket sequence.

Examples
input
Copy
3
)
()
(
output
Copy
2
input
Copy
2
()
()
output
Copy
4
Note

In the first example, suitable pairs are (2,2).

In the second example, any pair is suitable, namely (1,1),(1,2),(2,1),(2,2).

 

题意,寻找合法的括号匹配对数(1,3)和(3,1)不同

题解:感谢llw大佬讲题,思路是将每一组括号转化成对应的值来匹配,计算可匹配的值,相加即可得到答案

#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5+5;
typedef long long ll;
ll n,mx=0;
char str[maxn];
map<ll,ll> mp;
int main(){
    ios::sync_with_stdio(false);
    cin>>n;
    while(n--){
        cin>>str;
        ll flag=0,k=0,len=strlen(str);
        for(int i=0;i<len;i++){
              if(str[i]=='(') k++;
              else k--;
              //k=0的情况是这组数据符合要求
              //k>0的情况是左大于右
              //k<0的情况是右大于左
              if(k<0) flag=min(flag,k);
        }
        if(flag<0&&k>flag) continue;  //不合法的序列不用管,譬如())(
        else{
            //cout<<k<<" "<<flag<<endl;
            mp[k]++;
            mx=max(k,mx);
        }
    }
    ll ans=0;
    for(int i=0;i<=mx;i++){
        ans+=mp[i]*mp[-i];
    }
    cout<<ans<<endl;
    return 0;
}

 

相关文章: