poj 2774 最长公共子串 后缀数组

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;
const int MAXN=2222222;
char s1[MAXN],s2[MAXN];
int r[MAXN],lcp[MAXN];
int wa[MAXN], wb[MAXN], wv[MAXN], tmp[MAXN],a[MAXN];;
int sa[MAXN]; //index range 1~n value range 0~n-1
char s[MAXN];
int cmp(int *r, int a, int b, int l)
{
    return r[a] == r[b] && r[a + l] == r[b + l];
}
void da(int *r, int *sa, int n, int m)
{
    int i, j, p, *x = wa, *y = wb, *ws = tmp;
    ///对r中长度为1的子串进行基数排序
    for (i = 0; i < m; i++) ws[i] = 0;
    for (i = 0; i < n; i++) ws[x[i] = r[i]]++;
    for (i = 1; i < m; i++) ws[i] += ws[i - 1];
    for (i = n - 1; i >= 0; i--) sa[--ws[x[i]]] = i;
     ///对r中长度为j的子串进行基数排序
    for (j = 1, p = 1; p < n; j *= 2, m = p)
    {
        for (p = 0, 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 < n; i++) wv[i] = x[y[i]];
        for (i = 0; i < m; i++) ws[i] = 0;
        for (i = 0; i < n; i++) ws[wv[i]]++;
        for (i = 1; i < m; i++) ws[i] += ws[i - 1];
        for (i = n - 1; i >= 0; i--) sa[--ws[wv[i]]] = y[i];

        for (swap(x, y), p = 1, x[sa[0]] = 0, i = 1; i < n; i++)
            x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? p - 1 : p++;
    }
}
int rank[MAXN]; //index range 0~n-1 value range 1~n
int height[MAXN]; //index from 1   (height[1] = 0)
void calheight(int *r, int *sa, int n)
{
    int i, j, k = 0;
    for (i = 1; i <= n; ++i) rank[sa[i]] = i;
    for (i = 0; i < n; height[rank[i++]] = k)
        for (k ? k-- : 0, j = sa[rank[i] - 1]; r[i + k] == r[j + k]; ++k);
    return;
}

int main()
{
    //freopen("//media/学习/ACM/input.txt","r",stdin);
     while (~scanf("%s%s",s1,s2))
    {
        int i,j,k=0,len=0,n,m;
              n=strlen(s1);
              for (i=0;i<n;i++)
              {
                     r[k++]=s1[i]-'a'+2;
              }r[k++]=1;
              m=strlen(s2);
              for (i=0;i<m;i++)
              {
                 r[k++]=s2[i]-'a'+2;
              }r[k++]=0;
              da(r, sa, n+m+1,30);
              calheight(r, sa, n+m);
              for (i=2;i<k;i++)
              {
                    if((sa[i]>n&&sa[i-1]<n)||(sa[i-1]>n&&sa[i]<n))
                    len=max(len,height[i]);
              }
         printf("%d\n",len);
       }
       return 0;
}


你可能感兴趣的:(poj 2774 最长公共子串 后缀数组)