标签:
Given a string, we need to find the total number of its distinct substrings.
T- number of test cases. T<=20; Each test case consists of one string, whose length is <= 50000
For each test case output one number saying the number of distinct substrings.
Input: 2 CCCCC ABABA Output: 5 9
ac代码
#include<stdio.h> #include<string.h> #include<algorithm> #include<iostream> #define min(a,b) (a>b?b:a) #define max(a,b) (a>b?a:b) using namespace std; char str[50010]; int sa[50100],Rank[50100],rank2[50100],height[50010],c[50100],*x,*y,s[50100]; int n; void cmp(int n,int sz) { int i; memset(c,0,sizeof(c)); for(i=0;i<n;i++) c[x[y[i]]]++; for(i=1;i<sz;i++) c[i]+=c[i-1]; for(i=n-1;i>=0;i--) sa[--c[x[y[i]]]]=y[i]; } void build_sa(int *s,int n,int sz) { x=Rank,y=rank2; int i,j; for(i=0;i<n;i++) x[i]=s[i],y[i]=i; cmp(n,sz); int len; for(len=1;len<n;len<<=1) { int yid=0; for(i=n-len;i<n;i++) { y[yid++]=i; } for(i=0;i<n;i++) if(sa[i]>=len) y[yid++]=sa[i]-len; cmp(n,sz); swap(x,y); x[sa[0]]=yid=0; for(i=1;i<n;i++) { if(y[sa[i-1]]==y[sa[i]]&&sa[i-1]+len<n&&sa[i]+len<n&&y[sa[i-1]+len]==y[sa[i]+len]) x[sa[i]]=yid; else x[sa[i]]=++yid; } sz=yid+1; if(sz>=n) break; } for(i=0;i<n;i++) Rank[i]=x[i]; } void getHeight(int *s,int n) { int k=0; for(int i=0;i<n;i++) { if(Rank[i]==0) continue; k=max(0,k-1); int j=sa[Rank[i]-1]; while(s[i+k]==s[j+k]) k++; height[Rank[i]]=k; } } int main() { int t; scanf("%d",&t); while(t--) { int i; scanf("%s",str); int len=strlen(str); for(i=0;i<len;i++) s[i]=str[i]; s[len]=0; build_sa(s,len+1,260); getHeight(s,len); int sum=0; for(i=1;i<=len;i++) { sum+=len-sa[i]-height[i]; } printf("%d\n",sum); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
SPOJ 题目705 New Distinct Substrings(后缀数组,求不同的子串个数)
标签:
原文地址:http://blog.csdn.net/yu_ch_sh/article/details/47838809