[BZOJ4327][JSOI2012] 玄武密码 后缀自动机

诶KOI前复习一下板子
复习出来一堆问题
后缀自动机是两倍的点数啊

/**************************************************************
    Problem: 4327
    User: di4CoveRy
    Language: C++
    Result: Accepted
    Time:3420 ms
    Memory:479808 kb
****************************************************************/

#include 
#include 
#include 
#include 
#define N 10000050

using namespace std;
char s[N];
int len[2*N],lnk[2*N],ch[2*N][4],last,cnt,rt,n,m;
int get(int pos) {
    if (s[pos] == 'S') return 1;
    if (s[pos] == 'N') return 2;
    if (s[pos] == 'E') return 3;
    if (s[pos] == 'W') return 0;
    return assert(0),0;
}

void add(int pos) {
    int c = get(pos) , np = ++cnt , p = last;
    last = np; len[np] = len[p] + 1;
    while (p && !ch[p][c]) ch[p][c] = np , p = lnk[p];
    if (!p) lnk[np] = rt; else {
        int q = ch[p][c];
        if (len[q] == len[p] + 1) lnk[np] = q; else {
            int nq = ++cnt;
            len[nq] = len[p] + 1;
            memcpy(ch[nq],ch[q],sizeof(ch[q]));
            lnk[nq] = lnk[q];
            lnk[q] = lnk[np] = nq;
            while (p && ch[p][c] == q) ch[p][c] = nq , p = lnk[p];
        }
    }
}

int main() {
    #ifndef ONLINE_JUDGE
        freopen("1.in","r",stdin);
    #endif
    scanf("%d%d",&n,&m);
    scanf("%s",s+1);
    rt = last = ++cnt;
    for (int i=1;i<=n;i++) add(i);
    while (m--) {
        int ans = 0;
        scanf("%s",s+1); n = strlen(s+1);
        int p = rt;
        for (int _=1;_<=n;_++) {
            int c = get(_);
            if (!ch[p][c]) break; else {
                p = ch[p][c]; 
                ++ans;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(后缀自动机)