HDU 2328 Corporate Identity(后缀数组)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2328

题意:给出n个串,求n个串的最长的字典序最小的公共子串?

思路:二分。





int r[N],sa[N],wa[N],wb[N],wd[N],rank[N],h[N];



int cmp(int *r,int a,int b,int len)

{

    return r[a]==r[b]&&r[a+len]==r[b+len];

}



void da(int *r,int *sa,int n,int m)

{

    int i,j,p,*x=wa,*y=wb,*t;

    FOR0(i,m) wd[i]=0;

    FOR0(i,n) wd[x[i]=r[i]]++;

    FOR1(i,m-1) wd[i]+=wd[i-1];

    FORL0(i,n-1) sa[--wd[x[i]]]=i;

    for(j=1,p=1;p<n;j<<=1,m=p)

    {

        p=0;

        FOR(i,n-j,n-1) y[p++]=i;

        FOR0(i,n) if(sa[i]>=j) y[p++]=sa[i]-j;

        FOR0(i,m) wd[i]=0;

        FOR0(i,n) wd[x[i]]++;

        FOR1(i,m-1) wd[i]+=wd[i-1];

        FORL0(i,n-1) sa[--wd[x[y[i]]]]=y[i];

        t=x;x=y;y=t;p=1;x[sa[0]]=0;

        FOR1(i,n-1) x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;

    }

}







void calHeight(int *r,int *sa,int n)

{

    int i,j,k=0;

    FOR1(i,n) rank[sa[i]]=i;

    FOR0(i,n)

    {

        if(k) k--;

        j=sa[rank[i]-1];

        while(i+k<n&&j+k<n&&r[i+k]==r[j+k]) k++;

        h[rank[i]]=k;

    }

}



int n,m,b[N];

char s[N];



int start;





int OK(int x)

{

    int i,j,k,L,R,hash[4005];

    FOR1(i,n)

    {

        L=i;

        while(L<=n&&h[L]<x) L++;

        if(L>n) break;

        R=L;

        while(R<=n&&h[R]>=x) R++;

        clr(hash,0);

        FOR(j,L-1,R-1) if(b[sa[j]]!=-1) hash[b[sa[j]]]=1;

        FOR1(j,m) if(!hash[j]) break;

        if(j>m)

        {

            start=sa[L-1];

            return 1;

        }

        i=R;

    }

    return 0;

}





void print(int L)

{

    int i;

    FOR(i,start,start+L-1) putchar(r[i]);

    puts("");

}





void deal()

{

    int low=1,high=n,mid;

    while(low<=high)

    {

        mid=(low+high)>>1;

        if(OK(mid)) low=mid+1;

        else high=mid-1;

    }

    if(low<=n&&OK(low)) print(low);

    else if(high>=1&&OK(high)) print(high);

    else puts("IDENTITY LOST");

}





int main()

{

    while(scanf("%d",&m),m)

    {

        int i,k,j,L=0,x=130;

        FOR1(j,m)

        {

            RD(s); k=strlen(s);

            FOR0(i,k) r[L++]=s[i],b[L-1]=j;

            b[L]=-1;

            r[L++]=x++;

        }

        r[L]=0;

        da(r,sa,L+1,x);

        calHeight(r,sa,L);

        n=L;

        deal();

    }

    return 0;

}

  

你可能感兴趣的:(entity)