题解:CF1095E Almost Regular Bracket Sequence
先对字符串的下标进行加
尝试枚举每一个修改的位置
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
int n, S[N], cnt, ans, g[N], f[N];
string s;
int main() {
ios :: sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n >> s;
s = " " + s;
for(int i = 1; i <= n; i ++) {
S[i] = S[i - 1] + (s[i] == '(' ? 1 : -1);
if(S[i] < 0) cnt ++;
}
for(int i = n; i; i --) {
g[i] = g[i + 1];
if(S[i] <= 1) g[i] ++;
f[i] = f[i + 1];
if(S[i] < 0 && S[i] >= -2) f[i] ++;
}
for(int i = 1; i <= n; i ++) {
int sum = S[n] + (s[i] == '(' ? -2 : 2);
if(sum == 0) {
int cnt1 = cnt;
if(s[i] == ')') cnt1 -= f[i];
if(s[i] == '(' && g[i]) continue;
if(!cnt1) ans ++;
}
}
cout << ans;
return 0;
}