[SPOJ220]PHRASES - Relevant Phrases of Annihilation(后缀数组+二分)

题目描述

传送门
题意:给定 n 个字符串,求在每个字符串中至少出现两次且不重叠的最长子串。

题解

先将 n 个字符串连起来,中间用不相同的且没有出现在字符串中的字符隔开,求后缀数组。然后二分答案,再将后缀分组。判断的时候,要看是否有一组后缀在每个原来的字符串中至少出现两次,并且在每个原来的字符串中,后缀的起始位置的最大值与最小值之差是否不小于当前答案(判断能否做到不重叠)。

代码

#include
#include
#include
#include
using namespace std;
#define N 200005

int T,t,n,m,la,Max,inf,ans;
char a[N],s[N];
int *x,*y,X[N],Y[N],c[N],sa[N],height[N],rank[N];
int str[N],is_end[15],maxn[15],minn[15];

void clear()
{
    t=n=m=la=Max=inf=ans=0;
    memset(a,0,sizeof(a));memset(s,0,sizeof(s));
    memset(X,0,sizeof(X));memset(Y,0,sizeof(Y));memset(c,0,sizeof(c));
    memset(sa,0,sizeof(sa));memset(height,0,sizeof(height));memset(rank,0,sizeof(rank));
    memset(str,0,sizeof(str));memset(is_end,0,sizeof(is_end));memset(maxn,0,sizeof(maxn));memset(minn,0,sizeof(minn));
}
void build_sa()
{
    m=200;
    x=X,y=Y;
    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[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=0;i1];
        for (int i=n-1;i>=0;--i) sa[--c[x[y[i]]]]=y[i];

        swap(x,y);
        p=1,x[sa[0]]=0;
        for (int i=1;i1]]==y[sa[i]]&&((sa[i-1]+k1]+k]:-1)==(sa[i]+k1))?p-1:p++;
        if (p>n) break;
        m=p;
    }
}
void build_height()
{
    for (int i=0;iint k=0;height[0]=0;
    for (int i=0;iif (!rank[i]) continue;
        if (k) --k;
        int j=sa[rank[i]-1];
        while (i+kbool check(int mid)
{
    bool flag=false;
    int last=t-1;
    for (int i=t-1;i<=n;++i)
    {
        memset(maxn,-1,sizeof(maxn));
        memset(minn,127,sizeof(minn));inf=minn[0];
        if (height[i]for (int j=last;jbool pd=true;
            for (int j=1;j<=t;++j)
                if (maxn[j]==-1||minn[j]==inf||maxn[j]-minn[j]false;
                    break;
                }
            flag|=pd;
            last=i;
        }
    }
    return flag;
}
int find()
{
    int l=0,r=Max,mid,ans=0;
    while (l<=r)
    {
        mid=(l+r)>>1;
        if (check(mid)) ans=mid,l=mid+1;
        else r=mid-1;
    }
    return ans;
}
int main()
{
    scanf("%d\n",&T);
    while (T--)
    {
        clear();
        scanf("%d\n",&t);
        for (int i=1;i<=t;++i)
        {
            gets(a);la=strlen(a);
            Max=max(Max,la);
            for (int j=0;j1]=i;
            if (i!=t) s[n++]='$',str[n-1]=i;
            is_end[i]=n-1;
        }
        is_end[t]=n;
        build_sa();
        build_height();
        for (int i=0;iprintf("%d\n",ans);
    }
} 

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