CF653F Paper task の 题解
拿到题先想不考虑本质不同的串该怎么做。
即:求
我们可以考虑倒着扫描序列(原因在后面解答),分为一下两个方面考虑:
-
则一个 ) 匹配一个 (,也就是把 ) 设为1. ( 设为-1,将原字符串转化为一个只含1,-1的新整数序列
a 则满足\sum_{i=l}^r a[i] = 0 。 -
) 应该在 ( 的前面出现,也就是满足对于任意
通过上面两方面分析不难发现,可以枚举右端点,二分满足条件二的左边界(可以用ST表维护区间
回到本题,要求本质不同的字串可以想到在 sam 的 endpos 等价类上统计答案。同时,根据 endpos 的定义我们知道对于 sam 上一个节点包含的 sam 所能贡献的答案等于任意一个该店 endpos 集合的答案,所以可以选取 任意 一个 endpos 进行按刚刚的方法进行统计。使用后缀和而不是前缀和也是更符合 后缀自动机 的定义。
code :
// Created by fqr & cyx in 2024
#include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
#define ll long long
#define pb emplace_back
int ff,Ch;
template <typename T> inline void rd(T &x) {
x=0,ff=1,Ch=getchar();
while((Ch<'0'||Ch>'9') && Ch!='-') Ch=getchar();
if(Ch=='-')Ch=getchar(),ff=-1;
while(Ch>='0' && Ch<='9') {
x=(x<<1)+(x<<3)+Ch-'0';
Ch=getchar();
}
x*=ff;
}
template <typename T,typename ...Args> inline void rd(T &x,Args &...args) {
rd(x), rd(args...);
}
using namespace std;
const int N=1e6+5;
int n;
int lg[N],suf[N],lpos[N];
int f[N][19];
vector<int> pos[N<<1];
ll ans;
namespace sam {
int idx=1,lst;
struct vec {
int fa,len,edp;
int nxt[2];
} t[N<<1];
void ins(int c,int pos) {
int cur=++idx;
t[cur].len=t[lst].len+1;
t[cur].edp=pos;
int p=lst;
lst=cur;
while(p && !t[p].nxt[c]) {
t[p].nxt[c]=cur;
p=t[p].fa;
}
if(!p) return t[cur].fa=1,void();
int q=t[p].nxt[c];
if(t[q].len==t[p].len+1) return t[cur].fa=q,void();
int h=++idx;
t[h]=t[q];
t[h].len=t[p].len+1;
t[q].fa=t[cur].fa=h;
while(p && t[p].nxt[c]==q) {
t[p].nxt[c]=h;
p=t[p].fa;
}
}
void build(string &s) {
lst=1;
int tmp=1;
for(auto c:s)
ins(c==')',tmp),tmp++;
}
void calc() {
for(int i=2; i<=idx; i++) {
int mn=t[t[i].fa].len+1,mx=t[i].len;
int L=max(lpos[t[i].edp],t[i].edp-mx+1),R=t[i].edp-mn+1,val=suf[t[i].edp+1];
// cout<<"edp = "<<t[i].edp<<"\n"<<L<<" "<<R<<'\n';
if(L>R) continue;
auto &v=pos[val+n];
auto pl=lower_bound(v.begin(),v.end(),L)-v.begin();
auto pr=upper_bound(v.begin(),v.end(),R)-v.begin();
if(v[pr]>R) pr--;
if(pl>pr) continue;
// cout<<"Add "<<pr-pl+1<<'\n';
ans+=pr-pl+1;
}
}
}
void ST() {
for(int i=1; i<=n; i++)
f[i][0]=suf[i];
for(int i=2; i<=n; i++)
lg[i]=lg[i>>1]+1;
for(int j=1; j<=lg[n]; j++)
for(int i=1; i+(1<<j)-1<=n; i++)
f[i][j]=min(f[i][j-1],f[i+(1<<j-1)][j-1]);
}
int k;
int ask(int l,int r) {
k=lg[r-l+1];
return min(f[l][k],f[r-(1<<k)+1][k]);
}
signed main() {
#ifdef LOCAL
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
#endif
IOS;
string s;
cin>>n>>s;
sam::build(s);
s=" "+s;
for(int i=n; i; i--)
suf[i]=suf[i+1]+(s[i]==')'?1:-1);
for(int i=1; i<=n+1; i++)
pos[suf[i]+n].pb(i);
ST();
for(int i=n,l,r,mid; i; i--) {
l=1,r=i,lpos[i]=i+1;
while(l<=r) {
mid=l+r>>1;
if(ask(mid,i)>=suf[i+1])
lpos[i]=mid,r=mid-1;
else l=mid+1;
}
}
sam::calc();
cout<<ans;
return 0;
}
/*
10
()()()()()
0101010101
*/