54场周赛第三题
#include <iostream>
using namespace std;
const int N = 1e6 + 10, inf = 0x3f3f3f3f;
char s[N];
int nums[N];
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, cnt = 0;
cin >> n;
cin >> s + 1;
for(int i = 1; i <= n; i++){
if(s[i] == '(') cnt++;
}
if(abs(n - 2 * cnt) != 2) cout << "0" << endl;
else{
for(int i = 1; i <= n; i++){
if(s[i] =='(') nums[i] = 1;
else nums[i] = -1;
}
int pre = 0, suf = 0, l = n, r = 1;
for(int i = 1; i <= n; i++){
pre += nums[i];
if(pre < 0) {
l = i - 1;
break;
}
}
for(int i = n ; i >= 1; i--){
suf += nums[i];
if(suf > 0) {
r = i + 1;
break;
}
}
int res = 0;
if(cnt > n - cnt){
for(int i = r - 1; i <= l; i++)
if(s[i] =='(') ++res;
}
else{
for(int i = r; i <= l + 1; i++)
if(s[i] == ')') ++res;
}
cout << res << endl;
}
return 0;
}
经典的括号序列