【POJ 3261 Milk Patterns】 后缀数组/Hash+二分

POJ3261
题意就是找一个串中至少出现过k次的最长可重叠子串。
我们用一个串构造出后缀数组,之后进行GetHeight,然后二分答案进行验证,验证的时候将height数组分块,如果连续至少k-1个height都大于当前验证值,表示答案可行。
POJ3261代码

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e6+5;//开总串长度
int wa[maxn],wb[maxn],wsf[maxn],wv[maxn],sa[maxn];
int rank_[maxn],height[maxn],s[maxn];
int str1[maxn];
int n,k;
int cmp(int *r,int a,int b,int k)
{
    return r[a]==r[b]&&r[a+k]==r[b+k];
}

void getsa(int *r,int *sa,int n,int m)//n为添加0后的总长
{
    int i,j,p,*x=wa,*y=wb,*t;
    for(i=0; i<m; i++)  wsf[i]=0;
    for(i=0; i<=n; i++)  wsf[x[i]=r[i]]++;
    for(i=1; i<m; i++)  wsf[i]+=wsf[i-1];
    for(i=n; i>=0; i--)  sa[--wsf[x[i]]]=i;
    p=1;
    j=1;
    for(; p<=n; j*=2,m=p)
    {
        for(p=0,i=n+1-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++)  wsf[i]=0;
        for(i=0; i<=n; i++)  wsf[wv[i]]++;
        for(i=1; i<m; i++)  wsf[i]+=wsf[i-1];
        for(i=n; i>=0; i--)  sa[--wsf[wv[i]]]=y[i];
        t=x;
        x=y;
        y=t;
        x[sa[0]]=0;
        for(p=1,i=1; i<=n; i++)
            x[sa[i]]=cmp(y,sa[i-1],sa[i],j)? p-1:p++;
    }
}
void getheight(int *r,int n)//n为添加0后的总长
{
    int i,j,k=0;
    for(i=1; i<=n; i++)  rank_[sa[i]]=i;
    for(i=0; i<n; i++)
    {
        if(k)
            k--;
        else
            k=0;
        j=sa[rank_[i]-1];
        while(r[i+k]==r[j+k])
            k++;
        height[rank_[i]]=k;
    }
}
bool check(int L)
{
    int cnt=1;
    for(int i=2;i<=n-1;i++)
    {
        if(height[i]>=L) cnt++;
        else cnt=1;//存在中间某个小于L的,重新分块
        if(cnt==k) return true;//连续超过k-1个,直接返回true
    }
    return false;
}
int main()
{
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        for(int i=0;i<n;i++) scanf("%d",&str1[i]);
        str1[n++]=1000005;
        getsa(str1,sa,n,1000006);//上限为1e6+5
        getheight(str1,n);
        int l=0,r=n,mid;
        while(l<=r)
        {
            mid=(l+r)>>1;
            if(check(mid)) l=mid+1;
            else r=mid-1;
        }
        printf("%d\n",r);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38891827/article/details/80707850