bzoj 2938 AC自动机 + dfs判环

#include<bits/stdc++.h>
#define LL long long
#define ll long long
#define fi first
#define se second
#define mk make_pair
#define PII pair<int, int>
#define y1 skldjfskldjg
#define y2 skldfjsklejg

using namespace std;

const int N = 30000 + 7;
const int M = 1e7 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1000000007;

int n, m;
char s[N];

struct Ac {
    int ch[N][26], val[N], dp[N], f[N], tot, sz;
    int vis[N];
    Ac(int sz) {this->sz = sz;}
    void init() {tot = 0;};
    int newNode() {
        tot++; f[tot] = 0; val[tot] = 0;
        memset(ch[tot], 0, sizeof(ch[tot]));
        return tot;
    }
    inline int idx(char c) {return c - '0';}
    void addStr(char *s) {
        int u = 0;
        for(int i = 0; s[i]; i++) {
            int c = idx(s[i]);
            if(!ch[u][c]) ch[u][c] = newNode();
            u = ch[u][c];
        }
        val[u] = 1;
    }
    void build() {
        queue<int> que;
        for(int c = 0; c < sz; c++) {
            int v = ch[0][c];
            if(!v) ch[0][c] = 0;
            else f[v] = 0, que.push(v);
        }
        while(!que.empty()) {
            int u = que.front(); que.pop();
            val[u] |= val[f[u]];
            for(int c = 0; c < sz; c++) {
                int v = ch[u][c];
                if(!v) ch[u][c] = ch[f[u]][c];
                else f[v] = ch[f[u]][c], que.push(v);
            }
        }
    }

    bool dfs(int u) {
        vis[u] = -1;
        for(int c = 0; c < sz; c++) {
            int v = ch[u][c];
            if(val[v] || vis[v] == 1) continue;
            if(vis[v] == -1 || dfs(v)) return true;
        }
        vis[u] = 1;
        return false;
    }

    void solve() {
        memset(vis, 0, sizeof(vis));
        queue<int> que;
        que.push(0);
        printf("%s\n", dfs(0) ? "TAK" : "NIE");
    }
} ac(2);
int main() {
    ac.init();
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        scanf("%s", s);
        ac.addStr(s);
    }
    ac.build();
    ac.solve();
    return 0;
}


/*
2
abad
ba
-----
*/

 

posted @ 2018-08-17 10:49  NotNight  阅读(124)  评论(0编辑  收藏  举报