题意:
给定一个长度为 n n n 的括号序列,求有多少不同的子串是合法的括号序列。 ( n ≤ 5 × 1 0 5 ) (n \leq 5 × 10^5) (n≤5×105)
链接:
https://vjudge.net/problem/CodeForces-653F
解题思路:
不同子串,那么考虑后缀自动机上求解。对自动机上每个结点 u u u 求贡献,记其一个 e n d p o s endpos endpos 为 r r r,那么对应的子串为 [ l , r ] ( r − l e n [ u ] + 1 ≤ l ≤ r − l e n [ p a r [ u ] ] ) [l,~r](r - len[u] + 1 \leq l \leq r - len[par[u]]) [l, r](r−len[u]+1≤l≤r−len[par[u]]),子串 [ l , r ] [l,~r] [l, r] 合法就是经典的判定合法序列的问题,可以预处理出后缀和求解。
参考代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define sz(a) ((int)a.size())
#define pb push_back
#define lson (rt << 1)
#define rson (rt << 1 | 1)
#define gmid (l + r >> 1)
const int maxn = 1e6 + 5;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
vector<int> pi[maxn];
char s[maxn];
int has[256], sum[maxn], li[maxn], stk[maxn];
int nxt[maxn][2], par[maxn], len[maxn], id[maxn];
int n, cnt, last, top;
int add(int l){
++cnt; len[cnt] = l; return cnt;
}
void init(){
cnt = 0; last = add(0);
}
void insert(char ch){
int t = has[ch], p = last, cur;
cur = last = add(len[p] + 1);
while(p && !nxt[p][t]) nxt[p][t] = cur, p = par[p];
if(!p) { par[cur] = 1; return; }
int q = nxt[p][t];
if(len[q] == len[p] + 1) { par[cur] = q; return; }
int nq = add(len[p] + 1); id[nq] = id[q];
memcpy(nxt[nq], nxt[q], sizeof nxt[q]);
par[nq] = par[q], par[q] = par[cur] = nq;
while(p && nxt[p][t] == q) nxt[p][t] = nq, p = par[p];
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cin >> n >> s + 1;
init();
has['('] = 0, has[')'] = 1;
for(int i = 1; i <= n; ++i){
insert(s[i]);
id[last] = i;
}
for(int i = n; i >= 1; --i){
sum[i] = sum[i + 1] + (s[i] == '(' ? -1 : 1);
pi[sum[i] + n].pb(i);
}
for(int i = 0; i <= 2 * n; ++i){
reverse(pi[i].begin(), pi[i].end());
}
sum[0] = -inf;
for(int i = 1; i <= n + 1; ++i){
while(sum[i] <= sum[stk[top]]) --top;
li[i] = stk[top];
stk[++top] = i;
}
ll ret = 0;
for(int i = 2; i <= cnt; ++i){
int rm = id[i], l = rm - len[i] + 1, r = rm - len[par[i]];
l = max(l, li[rm + 1]);
if(l > r) continue;
int val = sum[rm + 1] + n, m = sz(pi[val]);
int p1 = lower_bound(pi[val].begin(), pi[val].end(), l) - pi[val].begin() + 1;
int p2 = upper_bound(pi[val].begin(), pi[val].end(), r) - pi[val].begin() + 1;
if(p1 > p2) continue;
ret += p2 - p1;
}
cout << ret << endl;
return 0;
}