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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值