POJ 2774 (最长公共子串)后缀数组+二分

题意:

题目链接:http://poj.org/problem?id=2774
求两个字符串中最长的公共子串


思路:

将两个串合并成一个,然后二分长度,判断时要看同一组中属于前一串的后缀喝属于后一串的后缀是否都存在。


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MAXN = 2e5 + 10;
const int INF = 0x3f3f3f3f;

int n, ns, nt;
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];
}

void build(int a[],int sa[],int rk[],int height[],int n,int m) {
    n++;
    int i, j, p, *x = t1, *y = t2;
    //第一轮基数排序,如果s的最大值很大,可改为快速排序
    for(i = 0; i < m; i++) c[i] = 0;
    for(i = 0; i < n; i++) c[x[i] = a[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;
        //直接利用sa数组排序第二关键字
        for(i = n-j; i < n; i++)y[p++] = i;//后面的j个数第二关键字为空的最小
        for(i = 0; i < n; i++)if(sa[i] >= j)y[p++] = sa[i] - j;
        //这样数组y保存的就是按照第二关键字排序的结果
        //基数排序第一关键字
        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];
        //根据sa和x数组计算新的x数组
        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;//下次基数排序的最大值
    }
    int k = 0;
    n--;
    for(i = 0; i <= n; i++)rk[sa[i]] = i;
    for(i = 0; i < n; i++)
    {
        if(k)   k--;
        j = sa[rk[i]-1];
        while(a[i+k] == a[j+k])
            k++;
        height[rk[i]] = k;
    }
}

int sa[MAXN], height[MAXN], rk[MAXN], a[MAXN];
char s[MAXN], t[MAXN];

bool check(int x) {
    int c1 = 0, c2 = 0;
    for (int i = 1; i <= n; i++) {
        if (height[i] >= x) {
            if (sa[i] + x - 1 < ns) ++c1;
            if (sa[i] >= ns) ++c2;
            if (c1 && c2) return true;
        }
        else {
            c1 = 0; c2 = 0;
            if (sa[i] + x - 1 < ns) ++c1;
            if (sa[i] >= ns) ++c2;
        }
    }
    if (c1 && c2) return true;
    return false;
}

int solve(int l, int r) {
    int res = 0;
    while (l <= r) {
        int m = (l + r) >> 1;
        if (check(m)) {
            res = m;
            l = m + 1;
        }
        else r = m - 1;
    }
    return res;
}

int main(){
    //freopen("in.txt", "r", stdin);
    scanf("%s%s", s, t);
    ns = strlen(s), nt = strlen(t);
    strcat(s, t);
    n = ns + nt;
    for (int i = 0; i < n; i++)
        a[i] = s[i];
    a[n] = 0;
    build(a, sa, rk, height, n, 128);
    printf("%d\n", solve(0, n));
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值