【POJ2774】后缀数组

POJ2774
链接
题意求两个串的最长公共子串,我们可以把两个串用一个特殊字符拼接,然后跑 S A h e i g h t ,由于最长公共子串肯定是 h e i g h t 中的某一个,而且要满足 s a [ i ] s a [ i 1 ] 分别属于两个串,所以只要跑一遍后缀数组遍历一遍 h e i g h t 就好了。
POJ2774代码

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxn 200005

int wa[maxn],wb[maxn],wsf[maxn],wv[maxn],sa[maxn];
int rank[maxn],height[maxn],s[maxn];
char str1[maxn],str2[maxn];
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)
{
    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)
{
    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;
    }
}

int main()
{
    int len,n;
    while(~scanf("%s%s",str1,str2))
    {
        n=0;
        len=strlen(str1);
        for(int i=0;i<len;i++)
            s[n++]=str1[i]-'a'+1;
        s[n++]=30;
        len=strlen(str2);
        for(int i=0;i<len;i++)
            s[n++]=str2[i]-'a'+1;
        s[n]=0;//两串拼接末尾添0
        getsa(s,sa,n,31);
        getheight(s,n);
        len=strlen(str1);
        int ans=0;
        for(int i=2;i<=n-1;i++)
        {
            if(height[i]>ans)
            {
                if(sa[i-1]>=0&&sa[i-1]<len&&sa[i]>len)
                    ans=max(ans,height[i]);
                if(sa[i]>=0&&sa[i]<len&&sa[i-1]>len)
                    ans=max(ans,height[i]);
            }
        }
        printf("%d\n",ans);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38891827/article/details/80345158
今日推荐