【TJOI2013】 单词

【题目链接】

         点击打开链接

【算法】

         AC自动机+递推

【代码】

       

#include<bits/stdc++.h>
using namespace std;
#define MAXN 200
const int MAXL = 1e6+5;

int i,N;
int pos[MAXN+10];
char s[MAXN+1][MAXL];

template <typename T> inline void read(T &x) {
    int f = 1; x = 0;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
    for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
    x *= f;
}

template <typename T> inline void write(T x) {
    if (x < 0) { putchar('-'); x = -x; }
    if (x > 9) write(x/10);
    putchar(x%10+'0');
}

template <typename T> inline void writeln(T x) {
    write(x);
    puts("");
}

struct AC_Automation {
    int tot;
    struct Trie {
        int sum,fail;
        int next[26];
    } trie[MAXL];
    inline void Insert(int id,char *s) {
        int i,len,x,root=0;
        len = strlen(s);
        for (i = 0; i < len; i++) {
            x = s[i] - 'a';
            if (!trie[root].next[x]) trie[root].next[x] = ++tot;
            root = trie[root].next[x];
            ++trie[root].sum;
        }
        pos[id] = root;
    }
    inline void rebuild() {
        int i,root,tmp,l=1,r=1;
        static int q[MAXL];
        q[1] = 0;
        trie[0].fail = -1;
        while (l <= r) {
            root = q[l]; l++;
            for (i = 0; i < 26; i++) {
                if (trie[root].next[i]) {
                    if (!root)
                        trie[trie[root].next[i]].fail = 0;
                    else {
                        tmp = trie[root].fail;
                        while (tmp != -1) {
                            if (trie[tmp].next[i]) {
                                trie[trie[root].next[i]].fail = trie[tmp].next[i];
                                break;
                            } 
                            tmp = trie[tmp].fail;
                        }
                        if (tmp == -1) trie[trie[root].next[i]].fail = 0;
                    }
                    q[++r] = trie[root].next[i];
                }
            }
        }
        for (i = r; i >= 1; i--) trie[trie[q[i]].fail].sum += trie[q[i]].sum;
    }    
    inline void output() {
        int i;
        for (i = 1; i <= N; i++) writeln(trie[pos[i]].sum);
    }
} ACAM;

int main() {
    
    read(N);
    for (i = 1; i <= N; i++) {
        gets(s[i]);
        ACAM.Insert(i,s[i]);    
    }
    ACAM.rebuild();
    ACAM.output();
    
    return 0;
}

 

posted @ 2018-02-19 17:38  evenbao  阅读(109)  评论(0编辑  收藏  举报