【BZOJ3172】[Tjoi2013]单词(AC自动机的小应用)

版权声明:本文为作者原创,若转载请注明地址。 https://blog.csdn.net/chenxiaoran666/article/details/81876466

点此看题面
大致题意:给你 N 个单词,请你求出每一个单词在这 N 个单词中出现的次数。


相关题目

这道题应该是洛谷上一道板子题的升级版。

【洛谷3796】【模板】AC自动机(加强版) 的题解详见博客【洛谷3796】【模板】AC自动机(加强版)


A C 自动机

这是一道 A C 自动机的简单运用题。

A C 自动机详见博客字符串匹配(三)——初学AC自动机


题解

一个比较暴力的做法,就是将这 N 个单词建一棵 T r i e ,然后将每个单词一个一个分别去跑 A C 自动机,可惜这样子会 T L E
进一步的,我们可以发现,相同的单词跑 A C 自动机的结果是一样的,为什么不一起跑呢?
这样就可以 A C 了。


代码

#include<bits/stdc++.h>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)<(y)?(x):(y))
#define LL long long
#define ull unsigned long long
#define swap(x,y) (x^=y,y^=x,x^=y)
#define tc() (A==B&&(B=(A=ff)+fread(ff,1,100000,stdin),A==B)?EOF:*A++)
#define pc(ch) (pp_<100000?pp[pp_++]=ch:(fwrite(pp,1,100000,stdout),pp[(pp_=0)++]=ch))
#define N 200
#define SUM 1000000
int pp_=0;char ff[100000],*A=ff,*B=ff,pp[100000];
using namespace std;
int n,rt=1,tot=1,ans,s[N+5];
string ss[N+5];
struct Trie
{
    int Son[26],Next,Cnt,Vis;
}node[SUM+5];
queue<int> q;
inline void read(int &x)
{
    x=0;static char ch;
    while(!isdigit(ch=tc()));
    while(x=(x<<3)+(x<<1)+ch-48,isdigit(ch=tc()));
}
inline void read_string(string &x)
{
    x="";static char ch;
    while(isspace(ch=tc()));
    while(x+=ch,!isspace(ch=tc())) if(!(~ch)) return;
}
inline void write(int x)
{
    if(x>9) write(x/10);
    pc(x%10+'0');
}
inline void Insert(int pos,string st)
{
    register int i,nxt,x=rt,len=st.length();
    for(i=0;i<len;++i)
    {
        if(!node[x].Son[nxt=st[i]-97]) node[x].Son[nxt]=++tot;
        x=node[x].Son[nxt];
    }
    ++node[x].Cnt,s[pos]=x;
}
inline void GetNext()
{
    register int i,k;q.push(rt);
    while(!q.empty())
    {
        k=q.front(),q.pop();
        for(i=0;i<26;++i)
        {
            if(k^rt)
            {
                if(!node[k].Son[i]) node[k].Son[i]=node[node[k].Next].Son[i];
                else node[node[k].Son[i]].Next=node[node[k].Next].Son[i],q.push(node[k].Son[i]);
            }
            else 
            {
                if(!node[k].Son[i]) node[k].Son[i]=rt;
                else node[node[k].Son[i]].Next=rt,q.push(node[k].Son[i]);
            }
        }
    }
}
inline void AC_Automation(string st,int val)//将字符串st作为文本串跑AC自动机,并用val记录st的重复个数
{
    register int i,j,x=rt,len=st.length();
    for(i=0;i<len;++i)
    {
        if(!(x=node[x].Son[st[i]-97])) {x=rt;continue;}
        int p=x;
        while(p^rt) node[p].Vis+=val,p=node[p].Next;//记录这个节点被val个字符串访问过了
    }
}
int main()
{
    register int i,j;
    for(read(n),i=1;i<=n;++i) read_string(ss[i]),Insert(i,ss[i]);
    for(GetNext(),i=1;i<=n;++i) 
        if(~node[s[i]].Cnt) AC_Automation(ss[i],node[s[i]].Cnt),node[s[i]].Cnt=-1;//一次性将所有与当前字符串相同的字符串一起跑AC自动机,并标记当前字符串已经跑过,不然会TLE
    for(i=1;i<=n;++i) write(node[s[i]].Vis),pc('\n');//输出每一个字符串在Trie上所对应的节点被访问的次数
    return fwrite(pp,1,pp_,stdout),0;
}

猜你喜欢

转载自blog.csdn.net/chenxiaoran666/article/details/81876466