SAM模板啦啦啦...

3 篇文章 0 订阅

刚从NanoApe学来的SAM..

SPOJ LCS 求两串的最长公共子串..

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int Maxn = 250010;
int F[Maxn*2], ch[Maxn*2][26], now, tot, d[Maxn*2];
char s[Maxn]; int len;
int _max ( int x, int y ){ return x > y ? x : y; }
int copy ( int p, int c ){
    int x = ++tot, y = ch[p][c];
    d[x] = d[p]+1;
    for ( int i = 0; i < 26; i ++ ) ch[x][i] = ch[y][i];
    F[x] = F[y]; F[y] = x;
    while ( ~p && ch[p][c] == y ){ ch[p][c] = x; p = F[p]; }
    return x;
}
void add ( int c ){
    int p, o;
    if ( p = ch[now][c] ){
        if ( d[p] != d[now]+1 ) copy ( now, c );
        now = ch[now][c];
    }
    else {
        d[o=++tot] = d[now]+1; p = now; now = o;
        while ( ~p && !ch[p][c] ) ch[p][c] = o, p = F[p];
        F[o] = ~p ? ( d[ch[p][c]] == d[p]+1 ? ch[p][c] : copy ( p, c ) ) : 0;
    }
}
int main (){
    int i, j, k;
    F[0] = -1; now = 0;
    scanf ( "%s", s+1 ); len = strlen (s+1);
    for ( i = 1; i <= len; i ++ ) add (s[i]-'a');
    scanf ( "%s", s+1 ); len = strlen (s+1);
    int ans = 0;
    int o = 0; now = 0;
    for ( i = 1; i <= len; i ++ ){
        int c = s[i]-'a';
        while ( ~o && !ch[o][c] ){ o = F[o]; now = o ? d[o] : 0; }
        if ( o < 0 ) o = now = 0; else o = ch[o][c], now ++;
        ans = _max ( ans, now );
    }
    printf ( "%d\n", ans );
    return 0;
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值