SPOJ-DISUBSTR - Distinct Substrings(后缀系列结构)
SPOJ-DISUBSTR - Distinct Substrings(后缀系列结构)
这是一个非常基础的模型了
后缀数组做法就是\(Ans=\sum n-sa[i]+1-lcp[i-1]\)
这题后缀自动机和后缀树没有什么特别大的差别
后缀自动机有两种做法
欢迎跳转总结博客
SA:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cctype>
#include<cstring>
#include<cassert>
using namespace std;
#define reg register
typedef long long ll;
#define rep(i,a,b) for(reg int i=a,i##end=b;i<=i##end;++i)
#define drep(i,a,b) for(reg int i=a,i##end=b;i>=i##end;--i)
template <class T> inline void cmax(T &a,T b){ if(a<b) a=b; }
template <class T> inline void cmin(T &a,T b){ if(a>b) a=b; }
char IO;
int rd(){
int s=0,f=0;
while(!isdigit(IO=getchar())) f|=(IO=='-');
do s=(s<<1)+(s<<3)+(IO^'0');
while(isdigit(IO=getchar()));
return f?-s:s;
}
const int N=20010,INF=1e9;
int n;
char s[N];
int cnt[N],sa[N],rk[N<<1],tmp[N],lcp[N];
void PreMake(){
rep(i,0,200) cnt[i]=0;
rep(i,1,n) cnt[(int)s[i]]++;
rep(i,1,200) cnt[i]+=cnt[i-1];
rep(i,1,n) rk[i]=cnt[(int)s[i]],sa[i]=i;
rep(i,n+1,n*2) rk[i]=0;
for(reg int k=1;k<=n;k<<=1) {
rep(i,0,n) cnt[i]=0;
rep(i,1,n) cnt[rk[i+k]]++;
rep(i,1,n) cnt[i]+=cnt[i-1];
drep(i,n,1) tmp[cnt[rk[i+k]]--]=i;
rep(i,0,n) cnt[i]=0;
rep(i,1,n) cnt[rk[i]]++;
rep(i,1,n) cnt[i]+=cnt[i-1];
drep(i,n,1) sa[cnt[rk[tmp[i]]]--]=tmp[i];
rep(i,1,n) tmp[sa[i]]=tmp[sa[i-1]]+(rk[sa[i]]!=rk[sa[i-1]]||rk[sa[i]+k]!=rk[sa[i-1]+k]);
rep(i,1,n) rk[i]=tmp[i];
}
int h=0;
rep(i,1,n) lcp[i]=0;
rep(i,1,n) {
int j=sa[rk[i]-1];
if(h) h--;
while(i+h<=n && j+h<=n && s[i+h]==s[j+h]) h++;
lcp[rk[i]-1]=h;
}
}
int main(){
rep(kase,1,rd()) {
scanf("%s",s+1),n=strlen(s+1);
PreMake();
ll ans=n*(n+1)/2;
rep(i,1,n) ans-=lcp[i];
printf("%lld\n",ans);
}
}
SAM:
#include<bits/stdc++.h>
using namespace std;
#define reg register
typedef long long ll;
#define rep(i,a,b) for(int i=a,i##end=b;i<=i##end;++i)
#define drep(i,a,b) for(int i=a,i##end=b;i>=i##end;--i)
#define pb push_back
template <class T> inline void cmin(T &a,T b){ ((a>b)&&(a=b)); }
template <class T> inline void cmax(T &a,T b){ ((a<b)&&(a=b)); }
char IO;
template<class T=int> T rd(){
T s=0;
int f=0;
while(!isdigit(IO=getchar())) if(IO=='-') f=1;
do s=(s<<1)+(s<<3)+(IO^'0');
while(isdigit(IO=getchar()));
return f?-s:s;
}
const int N=2010;
bool be;
int n;
char s[N];
int trans[N][26];
int stcnt,lst,len[N],link[N<<1];
void Init(){
link[0]=-1,len[0]=lst=0;
rep(i,0,stcnt) rep(j,0,25) trans[i][j]=0;
stcnt=0;
}
int ans;
void Extend(int c){
int cur=++stcnt,p=lst;
len[cur]=len[lst]+1;
while(~p && !trans[p][c]) trans[p][c]=cur,p=link[p];
if(p==-1) link[cur]=0;
else {
int q=trans[p][c];
if(len[q]==len[p]+1) link[cur]=q;
else {
int clone=++stcnt;
memcpy(trans[clone],trans[q],104);
link[clone]=link[q];
len[clone]=len[p]+1;
while(~p && trans[p][c]==q) trans[p][c]=clone,p=link[p];
link[cur]=link[q]=clone;
}
}
ans+=len[cur]-len[link[cur]];
lst=cur;
}
int main(){
rep(kase,1,rd()) {
scanf("%s",s+1),n=strlen(s+1);
Init();
ans=0;
rep(i,1,n) Extend(s[i]-'A');
printf("%d\n",ans);
}
}