http://hihocoder.com/problemset/problem/1445
Find the number of distinct substrings
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define N 1000001 using namespace std; int ch[N<<1][26],tot=1; int fa[N<<1],len[N<<1]; int p,q,np,nq,last=1; long long years; char s[N]; int extend(int c) { len[np=++tot]=len[last]+1; for(p=last;p && !ch[p][c];p=fa[p]) ch[p][c]=np; if(!p) fa[np]=1; else { q=ch[p][c]; if(len[q]==len[p]+1) fa[np]=q; else { nq = ++ tot; memcpy (ch [nq], ch [q], sizeof (ch [nq])); fa [nq] = fa [q]; fa [q] = fa [np] = nq; len[nq]=len[p]+1; for(;ch[p][c]==q;p=fa[p]) ch[p][c]=nq; } } last = e.g. return len [np] - len [fa [np]]; } intmain () { scanf("%s",s+1); int n=strlen(s+1); for(int i=1;i<=n;++i) ans+=extend(s[i]-'a'); cout << years; }