【hiho一下 第四周】Trie图

【题目链接】:http://hihocoder.com/problemset/problem/1036?sid=1092555

【题意】

【题解】

AC自动机的模板题;
在求有没有子串的时候;
注意要遍历所有后缀相同的情况;不然会漏解;
然后之前找过的就不要再找一遍了(即从那个状态找不能找到某个单词的终点);

【Number Of WA

1

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 110;
const int MAX = 1e6+100;

int n,a[MAX][27],f[MAX],cnt[MAX],tot = 1,flag[MAX];
queue <int> dl;
string s;

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    ios::sync_with_stdio(false),cin.tie(0);//scanf,puts,printf not use
    rep1(i,1,26) a[0][i] = 1;
    cin >> n;
    rep1(i,1,n)
    {
        cin >> s;
        int len = s.size();
        int now = 1;
        rep1(j,0,len-1)
        {
            int t = s[j]-'a'+1;
            if (a[now][t]==0) a[now][t]=++tot;
            now = a[now][t];
        }
        cnt[now]++;
    }
    f[1] = 0;
    dl.push(1);
    while (!dl.empty())
    {
        int x = dl.front();
        dl.pop();
        rep1(i,1,26)
        {
            if (a[x][i]==0) continue;
            int now = f[x];
            while (!a[now][i]) now = f[now];
            f[a[x][i]] = a[now][i];
            dl.push(a[x][i]);
        }
    }

    cin >> s;
    int len = s.size();
    int now = 1;
    rep1(i,0,len-1)
    {
        int t = s[i]-'a'+1;
        while (!a[now][t]) now = f[now];
        now = a[now][t];
        if (!flag[now])
        {
            for (int j = now;j;j=f[j])
            {
                if (flag[j]) break;
                flag[j] = true;
                if (cnt[j])
                    return cout <<"YES"<<endl,0;
            }
        }
    }
    cout <<"NO"<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626354.html