从便利店强盗手中救下的朴素店员,原来是同班天真可爱的辣妹!?
宝宝题。下文中的
对一个串的 )...))((...( 的子序列,我们取前缀左括号和后缀右括号之间的分割点作为操作位置就可以把序列变成 ((...(())...)),此时匹配完之后还会剩下一些左括号或者右括号,用插入补足,插入次数显然是左右括号个数之差。
插入和变换的贡献分别统计。把左括号记为
接下来考察变换的贡献,我们计数不用变换的子区间个数,拿总区间个数 (...(( 或者 )..))。以只剩下左括号为例,由于无右括号残余,所以满足
#include <bits/stdc++.h>
#define LL long long
#define ull unsigned long long
#define uint unsigned int
using namespace std;
const int N = 2e6 + 10;
int n, sum[N], cnt[N * 2], stk[N], tp, pos[N * 2], pre[N], nxt[N]; bool vis[N];
int cur[N], len;
int main() {
freopen(".in", "r", stdin); freopen(".out", "w", stdout);
ios::sync_with_stdio(false); cin.tie(0), cout.tie(0);
int _; cin >> _;
while (_ --) {
cin >> n; char c; cnt[n] ++;
for (int i = 1, s = 0; i <= n; i ++) {
cin >> c; s += (c == '(' ? 1 : -1); sum[i] = s;
pre[i] = pos[s + n]; pos[s + n] = i; cnt[s + n] ++; vis[i] = false;
}
LL Ans = 1ll * n * (n + 1) / 2;
LL curs = 0, curc = 0;
for (int i = 0; i <= n * 2; i ++) {
pos[i] = 0;
if (cnt[i]) {
Ans += cnt[i] * (curc * i - curs); curc += cnt[i], curs += 1ll * cnt[i] * i; cnt[i] = 0;
}
}
sum[n + 1] = -1e9; stk[0] = n + 1; stk[tp = 1] = n; nxt[n] = n + 1;
for (int i = n - 1; i >= 0; i --) {
while (tp && sum[stk[tp]] >= sum[i]) tp --;
Ans -= stk[tp] - i - 1; nxt[i] = stk[tp]; stk[++ tp] = i;
}
stk[0] = -1; stk[tp = 1] = 0;
for (int i = 1; i <= n; i ++) {
while (tp && sum[stk[tp]] >= sum[i]) tp --;
Ans -= i - stk[tp] - 1; stk[++ tp] = i;
}
for (int i = n; i >= 0; i --) if (!vis[i]) {
int t = i; len = 0;
while (t) cur[++ len] = t, t = pre[t], vis[t] = true;
if (!sum[i]) cur[++ len] = 0, vis[0] = false;
reverse(cur + 1, cur + 1 + len);
for (int j = 1, p = 0; j <= len; j ++) {
while (p < len && cur[p + 1] < nxt[cur[j]]) ++ p;
Ans += p - j;
}
}
cout << Ans << "\n";
}
return 0;
}