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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章