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
-----
*/

 

转载于:https://www.cnblogs.com/CJLHY/p/9492092.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值