SPOJ LCS(后缀自动机)

(http://acm.hust.edu.cn/vjudge/contest/view.action?cid=106071#problem/A)
题意:问串A,B的最长相同子串
解法:直接构造A的后缀自动机,搞一波lcp就好了。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <tr1/unordered_set>
//#include <tr1/unordered_map>
#include <bitset>
//#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;

#define lson l, m, ls[rt]
#define rson m+1, r, rs[rt]
#define inf 1e9
#define debug(a) cout << #a" = " << (a) << endl;
#define debugarry(a, n) for (int i = 0; i < (n); i++) { cout << #a"[" << i << "] = " << (a)[i] << endl; }
#define clr(x, y) memset(x, y, sizeof x)
#define ll long long
#define ull unsigned long long
#define FOR(i,a,b) \
    for(i=a;a<b?i<=b:i>=b;a<b?i++:i--)

const int maxn=2*250000+30;

struct suffix_automaton{
    int son[maxn][30],pre[maxn],step[maxn];
    int last,si;
    void pushback(int v){
        step[++si]=v;
        pre[si]=-1;
        clr(son[si],-1);
    }
    void Extend(int ch)
    {
        pushback(step[last]+1);
        int p=last,np=si;
        while(p!=-1&&son[p][ch]==-1)
            son[p][ch]=np,p=pre[p];
        if(p==-1) pre[np]=0;
        else{
            int q=son[p][ch];
            if(step[q]==step[p]+1) pre[np]=q;
            else{
                pushback(step[p]+1);
                int nq=si;
                memcpy(son[nq],son[q],sizeof son[q]);
                pre[nq]=pre[q];
                pre[q]=pre[np]=nq;
                while(p!=-1&&son[p][ch]==q)
                    son[p][ch]=nq,p=pre[p];
            }
        }
        last=np;
    }
    void init()
    {
        si=last=0;
        clr(son[0],-1);
        pre[0]=-1;
        step[0]=0;
    }
    int lcs(char *s){
        int l=0,ans=0,p=0;
        for(int i=0;s[i];i++){
            int c=s[i]-'a';
            while(p!=-1&&son[p][c]==-1)
                p=pre[p];
            if(p==-1) p=0,l=0;
            else{
                l=min(l,step[p]);
                p=son[p][c];
                l++;
            }
            ans=max(ans,l);
        }
        return ans;
    }
}su;

char s[maxn];

int main()
{
//  freopen("input.txt","r",stdin);
    //freopen("out2.txt","w",stdout);
    while(~scanf("%s",s))
    {
        su.init();
        for(int i=0;s[i];i++)
            su.Extend(s[i]-'a');
        scanf("%s",s);
        printf("%d\n",su.lcs(s));
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值