Codeforces C Bracket Sequences Concatenation Problem

C Bracket Sequences Concatenation Problem

C++ 11

#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
long long L[300000+10];
long long R[300000+10];
int main() {
int n;
string s;
cin>>n;
long long cnt =0;
for(int i=0;i<300000+10;i++) L[i]=R[i]=0;
for(int i=0;i<n;i++){
cin>>s;
int l = 0;
int r = 0;
for(int i=0;i<s.size();i++){
if(s[i]==')'&&r>0) r--;
else if(s[i]==')'&&r<=0) l++;
else if(s[i]=='(') r++;
}
if(l==0&&r==0) cnt+=1;
else if(l==0) R[r]+=1;
else if(r==0) L[l]+=1;
}
long long ans = cnt*cnt;
for(int i=0;i<300000+10;i++){
ans += R[i]*L[i];
}
cout<<ans<<endl;
return 0;
}

Python 3.7

from collections import defaultdict
if __name__ == "__main__":
n = int(input())
cnt = 0
L = defaultdict(int)
R = defaultdict(int)
for i in range(0,n):
s = list(input())
l = 0
r = 0
for item in s:
if item == '(' : r += 1
elif item == ')' and r>0: r -= 1
elif item == ')': l += 1
if l==0 and r==0: cnt+=1
elif l==0: R[r] += 1
elif r==0: L[l] += 1
ans = cnt*cnt
for item in L:
ans += L[item]*R[item]
print(ans)

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客