`
暴风雪
  • 浏览: 376501 次
  • 性别: Icon_minigender_2
  • 来自: 杭州
社区版块
存档分类
最新评论

[后缀数组]acdream 1430

 
阅读更多

大致题意:

      求出一个字符串(len<=10 000)中包含多少个出现至少两次的子串,且相同的子串互相不会覆盖

 

大致思路:

      求出后缀数组和height数组之后,对每个后缀,求出所有和她公共前缀大于0的后缀中,构成合法子串数量的最大值。

       一开始只想着用单纯O(n)的办法来解决,实际上由于字符串的特性,这个算法的覆盖度还是接近o(n)的

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int nMax = 20000;

int  num[nMax];
int sa[nMax], rank[nMax], height[nMax];
int wa[nMax], wb[nMax], wv[nMax], wd[nMax];

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 n, int m){          //  倍增算法 r为待匹配数组  n为总长度 m为字符范围
    int i, j, p, *x = wa, *y = wb, *t;
    for(i = 0; i < m; i ++) wd[i] = 0;
    for(i = 0; i < n; i ++) wd[x[i]=r[i]] ++;
    for(i = 1; i < m; i ++) wd[i] += wd[i-1];
    for(i = n-1; i >= 0; i --) sa[-- wd[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 ++) wd[i] = 0;
        for(i = 0; i < n; i ++) wd[wv[i]] ++;
        for(i = 1; i < m; i ++) wd[i] += wd[i-1];
        for(i = n-1; i >= 0; i --) sa[-- wd[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 ++;
        }
    }
}

void calHeight(int *r, int n){           //  求height数组。
    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 ++);
    }
}

int abs(int a){
    if(a>0)return a;
    return -a;
}
char str[nMax];
int main(){
    int i,j,k,sp,n,len;
    while(scanf("%s",str)!=EOF){
        sp=31;
        n=0;
        len=strlen(str);
        cout<<len<<endl;
        for(i=0;i<len;i++){
            num[i]=str[i]-'a'+1;
        }num[len]=0;
        da(num,len+1,sp);
        calHeight(num,len);
        int res=0,lcp,tmp;

        for(i=2;i<=len;i++){
            if(height[i]==height[i-1])continue;
            int h=lcp=height[i];
            tmp=0;
            for(j=i;j<=len;j++){
                if(height[j]==0)break;
                lcp=min(lcp,height[j]);
                int a=min(lcp,abs(sa[j]-sa[i-1]));
                if(a>height[i-1]&&a!=0){
                    tmp=max(tmp,a-height[i-1]);
                }
            }
            res+=tmp;
        }
        cout<<res<<endl;
    }
    return 0;
}

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics