HDU 2222 — Keywords Search

原题:http://acm.hdu.edu.cn/showproblem.php?pid=2222

题意:

给出n个模板以及文本,问文本中出现了多少个模板;


思路:

要注意有重复的模板,也是要算数的;

用val数组来计算每种模板的个数;用vis数组来表示单词的节点;


#include<cstdio>
#include<queue>
#include<cstring>
#include<string>

using namespace std;
const int maxnode = 500005;
const int sigma_size=26;
int ans;
struct AC_Automata
{
    int ch[maxnode][sigma_size];
    int val[maxnode];
    bool vis[maxnode];
    int f[maxnode];
    int last[maxnode];
    int sz;
    void init()
    {
        sz = 1;
        memset(ch[0], 0, sizeof(ch[0]));
        memset(vis, false, sizeof vis);
    }
    void insert(char *s)
    {
        int n = strlen(s), u = 0;
        for(int i = 0;i<n;i++)
        {
            int id = s[i]-'a';
            if(ch[u][id] == 0)
            {
                ch[u][id] = sz;
                memset(ch[sz], 0, sizeof(ch[sz]));
                val[sz++] = 0;
            }
            u = ch[u][id];
        }
        val[u]++;
        vis[u] = true;
    }
    void print(int i)
    {
        if(val[i])
        {
        	if(vis[i])
        	{
        		vis[i] = false;
        		ans+=val[i];
        	}
            print(last[i]);
        }
    }
    void find(char *s)
    {
        int n = strlen(s), j = 0;
        for(int i = 0;i<n;i++)
        {
            int id = s[i]-'a';
            while(j && ch[j][id] == 0) 	j = f[j];
            j = ch[j][id];
            if(val[j]) print(j);
            else if(val[last[j]]) print(last[j]);
        }
    }
    void getFail()
    {
        queue<int>q;
        last[0] = f[0] = 0;
        for(int i = 0;i<sigma_size;i++)
        {
            int u = ch[0][i];
            if(u)
            {
                f[u] = last[u] = 0;
                q.push(u);
            }
        }
        while(!q.empty())
        {
            int r = q.front(); 	q.pop();
            for(int i = 0;i<sigma_size;i++)
            {
                int u = ch[r][i];
                if(!u) continue;
                q.push(u);
                int v = f[r];
                while(v && ch[v][i] == 0) v = f[v];
                f[u] = ch[v][i];
                last[u] = val[f[u]]? f[u]:last[f[u]];
            }
        }
    }
};
AC_Automata ac;
char word[55];
char txt[1000005];
int main()
{
    int n, cas;
    scanf("%d", &cas);
    while(cas--)
    {
    	ans = 0;
    	scanf("%d\n", &n);
        ac.init();
        for(int i = 1;i<=n;i++)
        {
            scanf("%s", word);
            ac.insert(word);
        }
        ac.getFail();
        scanf("%s", txt);
        ac.find(txt);
        printf("%d\n", ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值