您的位置:首页 > 其它

后缀自动机(SAM)

2017-09-20 16:01 232 查看
记录一个菜逼的成长。。

好文推荐

个人感觉通俗易懂。

这里已hihocoder第128周为例。

hihocoder第128周

上面也有讲解。

题意:一个字符串里有几种不同的子串

答案:SAM所有状态的字符串数的和就是。每个状态的字符串数 = (max(s) - min(s) + 1)

max(s):是状态s所能表示的最大字符串长度

min(s)同理。

这里记下简易模板。

#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
typedef long long LL;
const int maxn = 1000000 + 10;
struct SAM{
int link[maxn<<1],go[maxn<<1][26],mxlen[maxn<<1],mnlen[maxn<<1];
int tot,last;
void init(){
tot = last = 0;
memset(go[0],-1,sizeof(go[0]));
link[0] = -1; mxlen[0] = 0;mnlen[0] = 0;
}
void ins(int c){
int p = last,cur = ++tot;
mxlen[cur] = mxlen[p] + 1;
memset(go[cur],-1,sizeof(go[cur]));
while(p != -1 && go[p][c] == -1)go[p][c] = cur,p = link[p];
if (p == -1) {
mnlen[cur] = 1;
link[cur] = 0;
}
else {
int q = go[p][c];
if (mxlen[q] == mxlen[p] + 1) mnlen[cur] = mxlen[q] + 1,link[cur] = q;
else {
int nq = ++tot;
memcpy(go[nq],go[q],sizeof(go[q]));
mxlen[nq] = mxlen[p] + 1;
link[nq] = link[q]; mnlen[q] = mxlen[nq] + 1;
link[cur] = nq; mnlen[cur] = mxlen[nq] + 1;
link[q] = nq;
while(p != -1 && go[p][c] == q) {
go[p][c] = nq,p = link[p];
}
mnlen[nq] = mxlen[link[nq]] + 1;
}
}
last = cur;
}
}sam;
char str[maxn];
int main()
{
while(~scanf("%s",str)) {
sam.init();
for (int i = 0; str[i]; i++)sam.ins(str[i] - 'a');
LL ans = 0;
for (int i = 1; i <= sam.tot; i++) {
ans += sam.mxlen[i] - sam.mnlen[i] + 1;
}
printf("%lld\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息