【BZOJ1717】[Usaco2006 Dec]Milk Patterns 产奶的模式(后缀数组+二分)

题目

传送门

题解

求重复至少k次的最长子串长度(可重叠)
求出sa数组和height数组之后,二分出一个长度,判断height数组中大于这个值的数是否有k个

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=2000001;

int n,k,m=200,s[maxn],x[maxn],y[maxn],c[maxn],sa[maxn],rnk[maxn],height[maxn];

void build_sa()
{
    for (int i=0; i<m; i++) c[i]=0;
    for (int i=0; i<n; i++) c[x[i]=s[i]]++;
    for (int i=1; i<m; i++) c[i]+=c[i-1];
    for (int i=n-1; i>=0; i--) sa[--c[x[i]]]=i;

    for (int k=1; k<=n; k<<=1)
    {
        int p=0;
        for (int i=n-k; i<n; i++) y[p++]=i;
        for (int i=0; i<n; i++) if (sa[i]>=k) y[p++]=sa[i]-k;

        for (int i=0; i<m; i++) c[i]=0;
        for (int i=0; i<n; i++) c[x[i]]++;
        for (int i=1; i<m; i++) c[i]+=c[i-1];
        for (int i=n-1; i>=0; i--) sa[--c[x[y[i]]]]=y[i];

        swap(x,y);
        p=1; height[sa[0]]=0;
        for (int i=0; i<n; i++)
            x[sa[i]] = y[sa[i-1]]==y[sa[i]] && ((sa[i-1]+k>=n?-1:y[sa[i-1]+k])==(sa[i]+k>=n?-1:y[sa[i]+k])) ? p-1:p++;
        if (p>n) break;
        m=p;
    }
}

void build_height()
{
    for (int i=0; i<n; i++) rnk[sa[i]]=i;
    int k=0; height[0]=0;
    for (int i=0; i<n; i++)
    {
        if (!rnk[i]) continue;
        if (k) k--;
        int j=sa[rnk[i]-1];
        while (i+k<n && j+k<n && s[i+k]==s[j+k]) k++;
        height[rnk[i]]=k;
    }
}

bool check(int x)
{
    int tot=1;
    for (int i=0; i<n; i++)
        if (height[i]>=x)
        {
            tot++;
            if (tot==k) return true;
        }
        else tot=1;
    return false;
}

int main()
{
    scanf("%d%d",&n,&k);
    for (int i=0; i<n; i++) scanf("%d",&s[i]);
    build_sa();
    build_height();
    int l=1,r=n;
    while (l<r)
    {
        int mid=(l+r)>>1;
        if (check(mid)) l=mid+1;
        else r=mid;
    }
    printf("%d",l-1);
    return 0;
}

总结

注意height数组的应用,二分在这里比较常用

猜你喜欢

转载自blog.csdn.net/A_Comme_Amour/article/details/79944857