SPOJ DISUBSTR - Distinct Substrings 後綴數組,轉化

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);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章