bzoj4516/洛谷P4070 [Sdoi2016]生成魔咒
题意:求每加进来一个数以后会有多少个不同的子串
方法:每加进来一个数,我们就考虑以它为结尾会有多少个就可以了,显然fa[p]之前都会加完了,所以新产生的就是
mx[p]−mx[fa[p]]
m
x
[
p
]
−
m
x
[
f
a
[
p
]
]
数会很大,所有用map记录就好
#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
#define N 200010
#define ll long long
int root,last,n,cnt=0,fa[N],mx[N];
ll ans=0;
map<int,int>son[N];
inline void ins(int ch){
int p=last,np=++cnt;last=np;mx[np]=mx[p]+1;
while(p&&!son[p][ch]) son[p][ch]=np,p=fa[p];
if(!p) fa[np]=root;
else{
int q=son[p][ch];
if(mx[q]==mx[p]+1) fa[np]=q;
else{
int nq=++cnt;mx[nq]=mx[p]+1;son[nq]=son[q];
fa[nq]=fa[q];fa[q]=fa[np]=nq;
while(son[p][ch]==q) son[p][ch]=nq,p=fa[p];
}
}ans+=(ll)mx[np]-(ll)mx[fa[np]];
}
int main(){
scanf("%d",&n);
last=root=++cnt;
for(int i=1;i<=n;i++){
int x;scanf("%d",&x);
ins(x);printf("%lld\n",ans);
}
return 0;
}