Description
魔咒串由许多魔咒字符组成,魔咒字符可以用数字表示。例如可以将魔咒字符 1、2 拼凑起来形成一个魔咒串 [1,2]。
一个魔咒串 S 的非空字串被称为魔咒串 S 的生成魔咒。
例如 S=[1,2,1] 时,它的生成魔咒有 [1]、[2]、[1,2]、[2,1]、[1,2,1] 五种。S=[1,1,1] 时,它的生成魔咒有 [1]、
[1,1]、[1,1,1] 三种。最初 S 为空串。共进行 n 次操作,每次操作是在 S 的结尾加入一个魔咒字符。每次操作后都
需要求出,当前的魔咒串 S 共有多少种生成魔咒。
第一行一个整数 n。
第二行 n 个数,第 i 个数表示第 i 次操作加入的魔咒字符。
1≤n≤100000。用来表示魔咒字符的数字 x 满足 1≤x≤10^9
Solution
经历了apio的后缀自动机讲解感觉自己又进一步(假
看到很多题解都是sa但是我太弱了只会sam怎么破
由于只在结尾加入字符,因此只需统计新增节点表示的字符串数量,即len[last]-len[fa[last]]
注意开LL
Code
#include <stdio.h>
#include <string.h>
#include <map>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define copy(x,t) memcpy(x,t,sizeof(x))
typedef long long LL;
const int N=400005;
int last=1,tot=1;
int fa[N],len[N];
LL ans;
std:: map <int,int> rec[N];
int read() {
int x=0,v=1; char ch=getchar();
for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
return x*v;
}
void extend(int ch) {
int p,q,np,nq;
p=last; np=last=++tot;
len[np]=len[p]+1;
for (;p&&!rec[p][ch];p=fa[p]) rec[p][ch]=np;
if (!p) fa[np]=1;
else {
q=rec[p][ch];
if (len[q]==len[p]+1) {
fa[np]=q;
} else {
nq=++tot; len[nq]=len[p]+1;
rec[nq]=rec[q];
fa[nq]=fa[q];
fa[np]=fa[q]=nq;
for (;p&&rec[p][ch]==q;p=fa[p]) rec[p][ch]=nq;
}
}
ans+=len[last]-len[fa[last]];
}
int main(void) {
for (int n=read();n--;) {
extend(read()); printf("%lld\n", ans);
}
return 0;
}