HDU - 5880 C - Family View (AC自动机)

版权声明:本文为蒟蒻原创文章,转载请注明出处哦~ https://blog.csdn.net/a54665sdgf/article/details/82384420

题目链接

题意:给你一些敏感词和一篇文章,让你把文章中所有的敏感词都和谐掉。

解法:AC自动机模板题,由于有比较大的实际应用价值,所以就搬上来了。

#define FRER() freopen("i.txt","r",stdin)
#define FREW() freopen("o.txt","w",stdout)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e6+10;
const int M=26;

int fail[N],nxt[N][M],val[N],nNode;
char s[N];
int n;

int ID(char ch)
{
    return tolower(ch)-'a';
}

int newNode()
{
    for(int i=0; i<M; ++i)nxt[nNode][i]=0;
    val[nNode]=0;
    return nNode++;
}

void Insert(const char* s)
{
    int u=0,len=strlen(s);
    for(int i=0; i<len; u=nxt[u][ID(s[i])],++i)
        if(!nxt[u][ID(s[i])])
            nxt[u][ID(s[i])]=newNode();
    val[u]=len;
}

void Getfail()
{
    queue<int> q;
    fail[0]=0;
    for(int i=0; i<M; ++i)
    {
        if(nxt[0][i])
        {
            fail[nxt[0][i]]=0;
            q.push(nxt[0][i]);
        }
        else
        {
            nxt[0][i]=0;
        }
    }
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        for(int i=0; i<M; ++i)
        {
            if(nxt[u][i])
            {
                fail[nxt[u][i]]=nxt[fail[u]][i];
                q.push(nxt[u][i]);
            }
            else
            {
                nxt[u][i]=nxt[fail[u]][i];
            }
        }
    }
}

void Ban(char* s)
{
    int len=strlen(s);
    for(int i=0,u=0; i<len; ++i)
    {
        if(!isalpha(s[i]))
        {
            u=0;
            continue;
        }
        u=nxt[u][ID(s[i])];
        for(int t=u; t; t=fail[t])
        {
            if(val[t])
            {
                for(int k=i; k>i-val[t]; --k)
                    s[k]='*';
            }
        }
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        nNode=0;
        newNode();
        scanf("%d",&n);
        while(n--)
        {
            scanf("%s",s);
            Insert(s);
        }
        Getfail();
        scanf(" ");
        gets(s);
        Ban(s);
        puts(s);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a54665sdgf/article/details/82384420