[SP1811] LCS - Longest Common Substring (suffix automaton)

Title link
to build a first string \ (the SAM \) , followed by a second string to match.
If you can go down to go down, then you can not jump parent tree's father, until you can go so far. If you jump \ (0 \) the still can not walk, re-match.

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1000010;
struct SAM{
    int ch[26];
    int len, fa;
}sam[MAXN << 1];
int las = 1, cnt = 1;
inline void add(int c){
    int p = las; int np = las = ++cnt;
    sam[np].len = sam[p].len + 1; 
    for(; p && !sam[p].ch[c]; p = sam[p].fa) sam[p].ch[c] = np;
    if(!p) sam[np].fa = 1;
    else{
        int q = sam[p].ch[c];
        if(sam[q].len == sam[p].len + 1) sam[np].fa = q;
        else{
            int nq = ++cnt; sam[nq] = sam[q];
            sam[nq].len = sam[p].len + 1;
            sam[q].fa = sam[np].fa = nq;
            for(; p && sam[p].ch[c] == q; p = sam[p].fa) sam[p].ch[c] = nq;
        }
    }
}
char a[MAXN], b[MAXN];
int ans;
int main(){
    scanf("%s", a + 1);
    scanf("%s", b + 1);
    int lena = strlen(a + 1), lenb = strlen(b + 1);
    for(int i = 1; i <= lena; ++i)
        add(a[i] - 'a');
    int p = 1, len = 0;
    for(int i = 1; i <= lenb; ++i){
        if(sam[p].ch[b[i] - 'a'])
            ++len, p = sam[p].ch[b[i] - 'a'];
        else{
            while(!sam[p].ch[b[i] - 'a'] && p) p = sam[p].fa;
            if(!p) p = 1, len = 0;
            else len = sam[p].len + 1, p = sam[p].ch[b[i] - 'a'];
        }
        ans = max(ans, len);
    }
    printf("%d\n", ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/Qihoo360/p/10992569.html