码迷,mamicode.com
首页 > 其他好文 > 详细

SPOJ 694 不同子串个数

时间:2017-08-14 23:36:55      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:不同   个数   blog   const   i++   cst   重复   scanf   argc   

一个论文题,求一个字符串有多少个不同的子串。

 

每个字符串可以看做一个后缀的前缀,然后,就转换为求每一个后缀中,不同的子串有多少。

每一个后缀,根据长度,可以提供len - sa[i] 个子串,但是,画图可以看出,有一些是重复的,height[i]。

#include <cstdio>
#include <cmath>
#include <cstring>


using namespace std;

const int maxn = 1000+5;
char str[maxn];

int wa[maxn],wb[maxn],wv[maxn],ws[maxn];
int sa[maxn];
int r[maxn];

int cmp(int *r,int a,int b,int l)
{
    return r[a]==r[b]&&r[a+l]==r[b+l];
}
void da(int *r,int *sa,int n,int m)
{
    int i,j,p,*x=wa,*y=wb,*t;
    for(i=0; i<m; i++) ws[i]=0;
    for(i=0; i<n; i++) ws[x[i]=r[i]]++;
    for(i=1; i<m; i++) ws[i]+=ws[i-1];
    for(i=n-1; i>=0; i--) sa[--ws[x[i]]]=i;
    for(j=1,p=1; p<n; j*=2,m=p)
    {
        for(p=0,i=n-j; i<n; i++) y[p++]=i;
        for(i=0; i<n; i++) if(sa[i]>=j) y[p++]=sa[i]-j;
        for(i=0; i<n; i++) wv[i]=x[y[i]];
        for(i=0; i<m; i++) ws[i]=0;
        for(i=0; i<n; i++) ws[wv[i]]++;
        for(i=1; i<m; i++) ws[i]+=ws[i-1];
        for(i=n-1; i>=0; i--) sa[--ws[wv[i]]]=y[i];
        for(t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1; i<n; i++)
            x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
    }
    return;
}

int rank[maxn],height[maxn];
void calheight(int *r,int *sa,int n)
{
    int i,j,k=0;
    for(i=1; i<=n; i++) rank[sa[i]]=i;
    for(i=0; i<n; height[rank[i++]]=k)
        for(k?k--:0,j=sa[rank[i]-1]; r[i+k]==r[j+k]; k++);
    return;
}


int main(int argc, char const *argv[])
{
    int t;
    scanf("%d",&t);
    while(t--) {
        scanf("%s",str);

        int len = strlen(str);
        for(int i=0;i<len;i++)
            r[i] = str[i];
        r[len] = 0;

        da(r,sa,len+1,256);

        calheight(r,sa,len);

        int sum = 0;
        for(int i=1;i<=len;i++) {
            sum+=len - sa[i] - height[i];
        }

        printf("%d\n",sum);

    }


    return 0;
}

 

SPOJ 694 不同子串个数

标签:不同   个数   blog   const   i++   cst   重复   scanf   argc   

原文地址:http://www.cnblogs.com/TreeDream/p/7360628.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!