码迷,mamicode.com
首页 > 其他好文 > 详细

最长公共子串

时间:2018-06-29 22:31:17      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:ring   cstring   last   return   最长公共子串   size   i++   emc   using   

/*
最长公共子串
用后缀自动机实现
首先建立一个串的后缀自动机
然后用另一个串在上面跑自动机即可

*/
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#define M 500010
using namespace std;
char s[M];
int ch[M][26], fa[M], len[M], last = 1, node = 1;

void insert(int c) {
    int f = last, p = ++node;
    last = p;
    len[p] = len[f] + 1;
    while(f && !ch[f][c]) ch[f][c] = p, f = fa[f];
    if(f == 0)fa[p] = 1;
    else {
        int x = ch[f][c];
        if(len[x] == len[f] + 1) fa[p] = x;
        else {
            int nx = ++node;
            fa[nx] = fa[x];
            len[nx] = len[f] + 1;
            fa[p] = fa[x] = nx;
            memcpy(ch[nx], ch[x], sizeof(ch[nx]));
        }
    }
}

int main() {
    scanf("%s", s);
    int l = strlen(s);
    for(int i = 0; i < l; i++) insert(s[i] - a);
    scanf("%s", s);
    l = strlen(s);
    int ans = 0;
    int now = 1, tmp = 0;
    for(int i = 0; i < l; i++) {
        int op = s[i] - a;
        if(ch[now][op]) {
            now = ch[now][op];
            tmp++;
        } else {
            while(now && !ch[now][op]) now = fa[now];
            if(now == 0) tmp = 0,now = 1;
            else tmp = len[now] + 1, now = ch[now][op];
        }
        ans = max(ans, tmp);
    }
    cout << ans << "\n";
    return 0 ;
}

 

最长公共子串

标签:ring   cstring   last   return   最长公共子串   size   i++   emc   using   

原文地址:https://www.cnblogs.com/luoyibujue/p/9245555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!