hihoCoder_1445_后缀自动机二·重复旋律5

时间:2023-03-10 01:33:01
hihoCoder_1445_后缀自动机二·重复旋律5

#1445 : 后缀自动机二·重复旋律5

时间限制:10000ms
单点时限:2000ms
内存限制:512MB

描述

小Hi平时的一大兴趣爱好就是演奏钢琴。我们知道一个音乐旋律被表示为一段数构成的数列。

现在小Hi想知道一部作品中出现了多少不同的旋律?

解题方法提示

输入

共一行,包含一个由小写字母构成的字符串。字符串长度不超过 1000000。

输出

一行一个整数,表示答案。

样例输入
aab
样例输出
    5
  • 后缀自动机中节点表示的后缀是连续的几个后缀
  • 这里连续的意味着以相同节点结尾的几个后缀的长度是连续的比如长度分别是3和4和5
  • 而当前节点的最短后缀长度是par指向节点的len+1
  • 因此当前节点所代表所有后缀的个数是以当前节点结尾的后缀的最大长度减最小长度加一
  • 而一般后缀自动机中对于当前节点的minlen是不用存储的,只要访问par节点的len即可,而后缀自动机中的len一般指maxlen,par和link都是同样一个意思
 #include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
typedef long long LL ;
typedef unsigned long long ULL ;
const int maxn = 1e6 + ;
const int inf = 0x3f3f3f3f ;
const int npos = - ;
const int mod = 1e9 + ;
const int mxx = + ;
const double eps = 1e- ;
const double PI = acos(-1.0) ; struct SAM{
int n, root, last, tot;
struct node{
int len;
int link, go[];
};
node state[maxn<<];
void init(char *str){
n=strlen(str);
tot=;
root=;
last=;
memset(&state,,sizeof(state));
}
void extend(int w){
tot++;
int p=last;
int np=tot;
state[np].len=state[p].len+;
while(p && state[p].go[w]==){
state[p].go[w]=np;
p=state[p].link;
}
if(p==){
state[np].link=root;
}else{
int q=state[p].go[w];
if(state[p].len+==state[q].len){
state[np].link=q;
}else{
tot++;
int nq=tot;
state[nq].len=state[p].len+;
memcpy(state[nq].go,state[q].go,sizeof(state[q].go));
state[nq].link=state[q].link;
state[q].link=nq;
state[np].link=nq;
while(p && state[p].go[w]==q){
state[p].go[w]=nq;
p=state[p].link;
}
}
}
last=np;
}
void build(char *str){
init(str);
for(int i=;i<n;i++)
extend(str[i]-'a');
}
LL substring_num(void){
LL ans=0LL;
for(int i=root;i<=tot;i++)
ans+=state[i].len-state[state[i].link].len;
return ans;
}
};
SAM A;
char str[maxn];
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
while(~scanf("%s",str)){
A.build(str);
printf("%lld\n",A.substring_num());
}
return ;
}