POJ 2774 Long Long Message 后缀数组

题目大意:

给出两个很长的串(长度分别 <= 100000) 求出两个串的最长公共子串的长度


大致思路:

用后缀数组的话很明显是个水题,将两个串连起来中间用一个没有出现的值隔开然后求出后缀数组和height数组

找到sa[i]及sa[i - 1]来自不同的串的时候height数组的最大值即可


代码如下:

Result  :  Accepted     Memory  :  5512 KB     Time  :  375 ms

/*
 * Author: Gatevin
 * Created Time:  2015/2/2 20:59:27
 * File Name: Iris_Freyja.cpp
 */
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;

#define maxn 233333

/*
 * 只需要将两个串连接起来,中间用一个不会出现的值隔开,结尾加上0
 * 求出height数组,之后只需要取当sa[i]与sa[i - 1]来自不同的两个串时
 * 对应height的值的最大值即可,很简单的后缀数组的应用
 */

/*
 * Doubling Algorithm求后缀数组
 */
int wa[maxn], wb[maxn], wv[maxn], Ws[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 *x = wa, *y = wb, *t, i, j, p;
    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;
    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(t = x, x = y, y = t, 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++;
    }
    return;
}

int rank[maxn], height[maxn];
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;
}

char s1[maxn >> 1];
char s2[maxn >> 1];
int s[maxn];
int sa[maxn];
int main()
{
    scanf("%s", s1);
    scanf("%s", s2);
    int n1 = strlen(s1);
    int n2 = strlen(s2);
    int n = n1 + 1 + n2;
    for(int i = 0; i < n1; i++)
        s[i] = s1[i] - 'a' + 1;
    s[n1] = 27;
    for(int i = 0; i < n2; i++)
        s[n1 + 1 + i] = s2[i] - 'a' + 1;
    s[n] = 0;
    da(s, sa, n + 1, 28);
    calheight(s, sa, n);
    int ans = 0;
    for(int i = 2; i <= n; i++)
        if(((lint)sa[i] - n1)*((lint)sa[i - 1] - n1) < 0)//判定两个起始位置是来自不同的串
            ans = max(height[i], ans);
    printf("%d\n", ans);
    return 0;
}


你可能感兴趣的:(long,long,message,poj,后缀数组,2774)