poj3261 (二分+后缀数组)可重叠的至少为k次最长重复字串

#include<stdio.h>
#include<string.h>
#define max 1000100
int rank[max],wa[max],wb[max],wv[max],wn[max];
int height[max],sa[max],r[max];
int N,K;
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++)wn[i]=0;
    for(i=0; i<n; i++)wn[x[i]=r[i]]++;
    for(i=1; i<m; i++)wn[i]+=wn[i-1];
    for(i=n-1; i>=0; i--)sa[--wn[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++)wn[i]=0;
        for(i=0; i<n; i++)wn[wv[i]]++;
        for(i=1; i<m; i++)wn[i]+=wn[i-1];
        for(i=n-1; i>=0; i--)sa[--wn[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;
}
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 i,j,sum,flag,ans,m;
    while(scanf("%d%d",&N,&K)!=EOF)
    {
        m=0;
        sum=0;
        ans=0;
        for(i=0; i<N; i++)
        {
            scanf("%d",&r[i]);
            if(m<r[i])
                m=r[i];
        }
        r[N]=0;
        da(r,sa,N+1,m+1);
        calheight(r,sa,N);
        int s=0,e=N;
        while(e>=s)
        {
            flag=0;
            int mid=(e+s)>>1;
            for(i=1; i<=N; i++)
            //height[]存的是排名相邻的两个后缀的最长公共前缀
                if(height[i]>=mid)
                    sum++;
                else
                {
                    if(sum+1>=K)
                    {
                        ans=mid;
                        flag=1;
                    }
                    sum=0;
                }
            if(sum+1>=K)
            {
                ans=mid;
                flag=1;
            }
            sum=0;
            if(flag)
                s=mid+1;
            else
                e=mid-1;
        }
        printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(poj3261 (二分+后缀数组)可重叠的至少为k次最长重复字串)