poj 2774 后缀数组模板

求两个字符串的最长公共子串。

将两个字符串连接为一个新字符串,并计算后缀数组和高度数组lcp。

然后检查后缀数组中所有相邻的后缀,其中后缀分别属于第一和第二个字符串的lcp的最大值就是答案。


#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
using namespace std;
#define maxn 200005


int r[maxn];
int rank[maxn],height[maxn],sa[maxn]; 
//sa[1~n]为有效值,sa[0]必定是n
//height[2~n]为有效值,height[i]代表是S[sa[i-1]...]和S[sa[i]...]的最长公公前缀lcp
int t1[maxn],t2[maxn],c[maxn];//辅助数组
bool cmp(int *r, int a, int b, int l)
{
    return r[a]==r[b]&&r[a+l]==r[b+l];
}
//logn次基数排序,O(nlogn)
void da(int *str,int n,int m) //n为字符串长度,m为字符最大值
{
    n++;
    int i,j,p,*x=t1, *y=t2;
    for(i=0; i<m; i++) c[i]=0;
    for(i=0; i<n; i++) c[x[i]=str[i]]++;
    for(i=1; i<m; i++) c[i]+=c[i-1];
    for(i=n-1; i>=0; i--) sa[--c[x[i]]]=i;
    for(j=1; j<=n; j<<=1){
        p=0;
        for(i=n-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<m; i++) c[i]=0;
        for(i=0; i<n; i++) c[x[y[i]]]++;
        for(i=1; i<m; i++) c[i]+=c[i-1];
        for(i=n-1; i>=0; i--) sa[--c[x[y[i]]]]=y[i];
        swap(x,y);
        p=1; x[sa[0]]=0;
        for(i=1; i<n; i++)
            x[sa[i]]=cmp(y, sa[i-1], sa[i], j)?p-1:p++;
        if(p>=n) break;
        m=p;
    }
    n--;
    int k=0;
    for(i=0; i<=n; i++) rank[sa[i]]=i;
    for(i=0; i<n; i++){
        if(k)k--;
        j=sa[rank[i]-1];
        while(str[i+k]==str[j+k]){k++;}
        height[rank[i]]=k;
    }
}
char s[maxn];

int main()
{
    while(scanf("%s", s)==1){
        int len=strlen(s);
        s[len]='#';
        scanf("%s", s+len+1);
        int n=strlen(s);
        for(int i=0; i<n; i++) r[i]=s[i];
        r[n]=0;
        da(r, n, 128);
        int ans=0;
        for(int i=1; i<n; i++)
            if( (sa[i]<len) != (sa[i+1]<len))
            ans=max(ans, height[i+1]);
        printf("%d\n", ans);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值