本文共 2993 字,大约阅读时间需要 9 分钟。
题意:问一个串的子串可以有多少种,就是将重复的去掉
思路:每个子串一定是某个后缀的前缀,对于某个后缀sa来说,它的最长前缀就是重复的个数,那么减去就好,而最长前缀可以通过后缀数组的sa数组线性求出
//// main.cpp// 后缀数组//// Created by liuzhe on 17/2/5.// Copyright © 2017年 my_code. All rights reserved.// SPOJ 694#include#include #include #include #include using namespace std;const int maxn = 50010;int wa[maxn],wb[maxn],wv[maxn],ww[maxn];int sa[maxn],lcp[maxn],rank[maxn],rank1[maxn];char str[maxn];int t,nn;inline bool cmp(int *r,int a,int b,int len){ return r[a]==r[b]&&r[a+len]==r[b+len];}void construct_sa(int n,int m){ int i,j,p,*x=wa,*y=wb,*t; //n++;//why? for(i=0;i =0;i--) sa[--ww[x[i]]] = i; for(j=p=1;p <<=1,m=p) { for(p=0,i=n-j;i =j) y[p++] = sa[i]-j; } for(i=0;i =0;i--) sa[--ww[wv[i]]] = y[i]; for(t=x,x=y,y=t,x[sa[0]]=0,p=i=1;i 0) h--; for(;j+h
//// main.cpp// 后缀数组//// Created by liuzhe on 17/2/5.// Copyright © 2017年 my_code. All rights reserved.// SPOJ 705#include#include #include #include #include using namespace std;const int maxn = 50010;int wa[maxn],wb[maxn],wv[maxn],ww[maxn];int sa[maxn],lcp[maxn],rank[maxn],rank1[maxn];char str[maxn];int t,nn;inline bool cmp(int *r,int a,int b,int len){ return r[a]==r[b]&&r[a+len]==r[b+len];}void construct_sa(int n,int m){ int i,j,p,*x=wa,*y=wb,*t; //n++;//why? for(i=0;i =0;i--) sa[--ww[x[i]]] = i; for(j=p=1;p <<=1,m=p) { for(p=0,i=n-j;i =j) y[p++] = sa[i]-j; } for(i=0;i =0;i--) sa[--ww[wv[i]]] = y[i]; for(t=x,x=y,y=t,x[sa[0]]=0,p=i=1;i 0) h--; for(;j+h
spoj 694另解
#include#include #include #include #include using namespace std; typedef long long ll; const int inf=0x3f3f3f3f; const int maxn=1010; int n,k,cnt; int rank1[maxn],sa[maxn],tmp[maxn],lcp[maxn]; char str[maxn]; bool compare_sa(int i,int j)
{ if(rank1[i]!=rank1[j])
return rank1[i]
{ int ri=i+k<=n? rank1[i+k]:-1; int rj=j+k<=n? rank1[j+k]:-1; return ri
{ for(int i=0;i<=n;i++)
{ sa[i]=i; rank1[i]=i
{ sort(sa,sa+n+1,compare_sa); tmp[sa[0]]=0; for(int i=1;i<=n;i++)
{ tmp[sa[i]]=tmp[sa[i-1]]+(compare_sa(sa[i-1],sa[i])?1:0); } for(int i=0;i<=n;i++) rank1[i]=tmp[i]; } } void construct_lcp()
{ for(int i=0;i<=n;i++) rank1[sa[i]]=i; int h=0; lcp[0]=0; for(int i=0;i
{ int j=sa[rank1[i]-1]; if(h>0) h--; for(;j+h
if(str[i+h]!=str[j+h])
break; lcp[rank1[i]-1]=h; } } int main()
{ int T; scanf("%d",&T); while(T—)
{ scanf("%s",str); n=strlen(str); int ans=(n+1)*n/2; cnt=0; construct_sa(); construct_lcp(); for(int i=0;i
cnt+=lcp[i]; printf("%d\n",ans-cnt); } return 0; }
转载地址:http://ojali.baihongyu.com/