hdu 4622 Reincarnation(後綴自動機,入門級)

題意:
求字符串任意字串的不同字串數。
思路:
用後綴自動機可以做到 O(n2) 預處理,O(1) 回答查詢。
不過我的代碼跑了 1000+ms
別人的代碼可以跑到 100ms-200ms。。
VJ的記錄

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <set>
#include <queue>
#include <cmath>
using namespace std;
#define rep(i, s, t) for(int (i)=(s);(i)<=(t);++(i))
const int N = 2005;
typedef long long LL;

struct State {
    State *link, *go[26];
    int len;
    void clear() {
        link = 0; len = 0; memset(go, 0, sizeof(go));
    }
    int calc() {
        if ( link == 0 ) return 0;
        return len - link->len;
    }
} *root, *last, *cur;

const int MaxLength = N;
State statePool[MaxLength*2];

void init() {
    cur = statePool;
    root = last = cur ++;
    root->clear();
}

int tot = 0;

void sa_insert(int ch) {
    //cout << "Insert " << (char)ch << endl;
    ch -= 'a';
    State *p = last;
    State *np = cur ++;
    np->clear();
    np->len = p->len + 1;
    while ( p && !p->go[ch] ) {
        p->go[ch] = np; p = p->link;
    }
    if ( p == 0 ) {
        np->link = root;
    } else {
        State *q = p->go[ch];
        if ( p->len + 1 == q->len ) {
            np->link = q;
        } else {
            State *nq = cur ++;
            nq->clear();
            memcpy(nq->go, q->go, sizeof(q->go));

            tot -= q->calc();

            nq->len = p->len + 1;
            nq->link = q->link;
            q->link = nq;
            np->link = nq;

            tot += q->calc() + nq->calc();

            while( p && p->go[ch] == q ) {
                p->go[ch] = nq; p = p->link;
            }
        }
    }
    tot += np->calc();
    last = np;
}

int cnt[N][N], n;
char buf[N];

int main() {
#ifdef _LOCA_ENV_
    freopen("input.in", "r", stdin);
#endif // _LOCA_ENV
    int t;
    scanf("%d", &t);
    while ( t -- ) {
        scanf("%s", buf);
        //cout << buf << endl;
        scanf("%d", &n);
        int len = strlen(buf);
        rep(i, 0, len-1) {
            init();
            tot = 0;
            rep(j, i, len-1) {
                sa_insert(buf[j]);
                cnt[i][j] = tot;
            }
        }
        rep(i, 1, n) {
            int l, r;
            scanf("%d%d", &l, &r);
            -- l, -- r;
            printf("%d\n", cnt[l][r]);
        }
    }
    return 0;
}
發佈了278 篇原創文章 · 獲贊 10 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章