后缀自动机(SAM)-模板记录/好文推荐

记录一个菜逼的成长。。

好文推荐
个人感觉通俗易懂。

这里已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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值