SPOJ LCS(尾碼自動機)

來源:互聯網
上載者:User

(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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.