SPOJDISUBSTR - Distinct Substrings 后缀数组,转化

    xiaoxiao2021-04-15  24

    DISUBSTR - Distinct Substrings

    no tags 

    Given a string, we need to find the total number of its distinct substrings.

    Input

    T- number of test cases. T<=20; Each test case consists of one string, whose length is <= 1000

    Output

    For each test case output one number saying the number of distinct substrings.

    Example

    Sample Input: 2 CCCCC ABABA

    Sample Output: 5 9

    Explanation for the testcase with string ABABA:  len=1 : A,B len=2 : AB,BA len=3 : ABA,BAB len=4 : ABAB,BABA len=5 : ABABA

    Thus, total number of distinct substrings is 9.

    用后缀数组做,感觉太强啦,考虑dc3的基数排序可以拿到O(n)的复杂度,这也是最好的复杂度了

    但是为了好写我用的倍增,而且题目中也没有给出字符是仅有大写字母还是可能含有特殊字符,所以用的是倍增+归并排序的写法

    之所以用归并排序而不用快速排序的理由是,论文上是用了计数排序来完成倍增,而它每一次计数排序都是能够保证稳定性的

    由于第二关键字是通过上一次的结果直接算出来,因此这就要求对第一关键字排序是必须要保持稳定性,不然会打乱第二关键字的顺序

    这道题实际上是论文的板题。。。

    因为一个子串必然是一个后缀的前缀

    具体做法是按照sa[1]->sa[len]的方向计算,每一次可以有len-sa[i]+1个新子串(这个后缀的前缀数),可是考虑重复的问题,需要减去height[i]也就是和上一个后缀的lcp

    PS:我这里因为有一个raw[len++]=-1的操作,因此len和sa的全都加了1,实际上在计算的时候应该是len-sa[i]-1

    #include <iostream> #include <cstring> #include <algorithm> using namespace std; const int maxm=1010; int times,len,wa[maxm],wb[maxm],raw[maxm],sa[maxm],*x,*y,height[maxm],_rank[maxm]; void da(),calheight(); bool cmp(int* r,int a,int b,int L){return r[a]==r[b]&&r[a+L]==r[b+L];} char c; int main(){ ios_base::sync_with_stdio(false); (cin>>times).get(); while(times--){ for(len=0;cin.get(c)&&c!='\n';raw[len++]=c); raw[len++]=-1; da(); calheight(); int ans=0; for(int i=1;i<len;++i) ans+=len-sa[i]-height[i]-1; cout<<ans<<endl; } return 0; } void da(){ int i,j,p; x=wa,y=wb; for(int i=0;i<len;++i) sa[i]=i,x[i]=raw[i]; stable_sort(sa,sa+len,[](int a,int b){return x[a]<x[b];}); for(j=p=1;p<len;j<<=1){ for(p=0,i=len-j;i<len;++i)y[p++]=i; for(i=0;i<len;++i)if(sa[i]>=j)y[p++]=sa[i]-j; for(i=0;i<len;++i)sa[i]=y[i]; stable_sort(sa,sa+len,[](int a,int b){return x[a]<x[b];}); for(swap(x,y),p=1,x[sa[0]]=0,i=1;i<len;++i) x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++; } } void calheight(){ for(int i=0;i<len;++i)_rank[sa[i]]=i; for(int i=0,j,k=0;i<len;height[_rank[i++]]=k) for(k?k--:0,j=sa[_rank[i]-1];raw[i+k]==raw[j+k];++k); }

    转载请注明原文地址: https://ju.6miu.com/read-671456.html

    最新回复(0)