HDU2222 Keywords Search

本文深入探讨了AC自动机与Trie树在字符串匹配问题中的应用,通过一道实战题目,详细讲解了如何利用这两种数据结构进行高效字符串搜索。文章提供了完整的代码实现,包括初始化Trie树、构建AC自动机以及扫描文本字符串的过程,同时强调了访问过节点的标记对于避免重复计算的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ac自动机裸题,但我还是写的trie图。

还有,访问过的点要打标记,不然会tle。

代码:

#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int T,n,tot;
char s[60],st[1000050];
struct Trie
{
    int ch[28];
    int f,w,vis;
}tr[500500];
void init()
{
    for(int i=0;i<=tot;i++)
    {
        tr[i].f = tr[i].w = tr[i].vis = 0;
        for(int j=1;j<=26;j++)
            tr[i].ch[j] = 0;
    }
    tot=0;
}
void trie_pic()
{
    queue<int>q;
    for(int i=1;i<=26;i++)
        if(tr[0].ch[i])
            q.push(tr[0].ch[i]);
    while(!q.empty())
    {
        int u = q.front();
        q.pop();
        for(int i=1;i<=26;i++)
        {
            int &v = tr[u].ch[i];
            if(!v)
            {
                v = tr[tr[u].f].ch[i];
                continue;
            }
            tr[v].f = tr[tr[u].f].ch[i];
            q.push(v);
        }
    }
}
int main()
{
    scanf("%d",&T);
    while(T--)
    {
        init();
        tr[0].vis=1;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%s",s+1);
            int len = strlen(s+1);
            int u = 0;
            for(int j=1;j<=len;j++)
            {
                int c = s[j]-'a'+1;
                if(!tr[u].ch[c])tr[u].ch[c] = ++tot;
                u = tr[u].ch[c];
            }
            tr[u].w++;
        }
        trie_pic();
        scanf("%s",st+1);
        int u = 0,now,ans = 0,len = strlen(st+1);
        for(int i=1;i<=len;i++)
        {
            int c = st[i]-'a'+1;
            u = tr[u].ch[c];
            now = u;
            while(!tr[now].vis)
            {
                ans+=tr[now].w;
                tr[now].w=0;
                tr[now].vis=1;
                now=tr[now].f;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/LiGuanlin1124/p/9668290.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值