[BZOJ3796]Mushroom追妹纸(hash+后缀数组+二分)

题目描述

传送门

题解

把s1和s2接在一起,中间加一个分隔符
预处理出s3在s1和s2中的哪些位置出现过(hash)
求出sa和height,容易知道答案一定在相邻的两个在不同串里的后缀中产生
对于每一对相邻的后缀,二分一下满足条件的最大长度,即没有出现s3(前缀和)
时间复杂度 O(nlogn)

代码

#include
#include
#include
#include
#include
using namespace std;
#define N 200005
#define sz 17
#define UL unsigned long long

const UL S=2000001001LL;
char s1[N],s2[N],s3[N],s[N];
int l[5],n,m,p,ans,*x,*y,X[N],Y[N],c[N],sa[N],height[N],rank[N],flag[N];
UL mi[N],hashs,hash3;

void hash_init()
{
    mi[0]=1;for (int i=1;i<=n;++i) mi[i]=mi[i-1]*S;
    hash3=0;
    for (int i=0;i3];++i) hash3+=(UL)s3[i]*mi[l[3]-i-1];
    if (l[3]<=n)
    {
        hashs=0;
        for (int i=0;i3];++i) hashs+=(UL)s[i]*mi[l[3]-i-1];
        if (hashs==hash3) ++flag[0];
        for (int i=1;i3]+1;++i)
        {
            hashs=(hashs-(UL)s[i-1]*mi[l[3]-1])*S+(UL)s[i+l[3]-1];
            if (hashs==hash3) ++flag[i];
        }
        for (int i=1;i1];
    }
}
void build_sa()
{
    m=200;
    x=X,y=Y;
    for (int i=0;ifor (int i=1;i1];
    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;ifor (int i=0;iif (sa[i]>=k) y[p++]=sa[i]-k;

        for (int i=0;i0;
        for (int i=0;ifor (int i=1;i1];
        for (int i=n-1;i>=0;--i) sa[--c[x[y[i]]]]=y[i];

        p=1;
        swap(x,y);x[sa[0]]=0;
        for (int i=1;i1]]==y[sa[i]])&&((sa[i-1]+k1]+k]:-1)==(sa[i]+k1))?p-1:p++;
        m=p;
        if (p>=n) break;
    }
}
void build_height()
{
    for (int i=0;iint k=0;
    for (int i=0;iif (!rank[i]) continue;
        int j=sa[rank[i]-1];
        if (k) --k;
        while (i+kint num(int id)
{
    if (sa[id]<=l[1]) return 1;
    return 2;
}
bool check(int id,int jd,int len)
{
    if (len3]) return 1;
    len-=l[3];
    return !(flag[id+len]-(id?flag[id-1]:0))&&!(flag[jd+len]-(jd?flag[jd-1]:0));
}
int main()
{
    scanf("%s",s1);scanf("%s",s2);scanf("%s",s3);
    l[1]=strlen(s1),l[2]=strlen(s2),l[3]=strlen(s3);
    for (int i=0;i1];++i) s[n++]=s1[i];s[n++]='$';l[1]=n-2;
    for (int i=0;i2];++i) s[n++]=s2[i];l[2]=n-1;
    hash_init();
    build_sa();
    build_height();
    for (int i=0;iint t=num(i);
        height[i]=min(height[i],l[t]-sa[i]+1);
    }
    for (int i=1;iif (s[sa[i]]=='$') continue;
        if (num(i)==num(i-1)) continue;
        int l=0,r=height[i],mid;
        while (l<=r)
        {
            mid=(l+r)>>1;
            if (check(sa[i-1],sa[i],mid))
                ans=max(ans,mid),l=mid+1;
            else r=mid-1;
        }
    }
    printf("%d\n",ans);
}

你可能感兴趣的:(题解,hash,后缀数组,二分)