HDU2222 Keywords Search [AC自动机]

本文介绍了一个基于Aho-Corasick算法的图像检索系统关键词匹配案例。该系统能够高效处理大量关键词,在图像描述中查找匹配项。文章详细解释了算法原理、实现细节及优化方法。

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

Keywords Search
Time Limit: 1000MS
Memory Limit: 131072KB
64bit IO Format: %I64d & %I64u

Description
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Wiskey also wants to bring this feature to his image retrieval system.
Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.
To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.

Input
First line will contain one integer means how many cases will follow by.
Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)
Each keyword will only contains characters ‘a’-‘z’, and the length will be not longer than 50.
The last line is the description, and the length will be not longer than 1000000.

Output
Print how many keywords are contained in the description.

Sample Input
1
5
she
he
say
shr
her
yasherhs

Sample Output
3


Aho-Corasick automaton 裸题
注意访问过的字符串在单词节点清零
节点个数: 最大长度*单词数

普通带fail写法

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<iomanip>
#include<ctime>
#include<climits>
#include<cctype>
#include<algorithm>
#ifdef WIN32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=10000*50+5;
const int maxlen=1000005;
const int SIGMA_SIZE=26;
inline int idx(char c) { return c-'a'; }
struct Node
{
    int val;//>0 the end, 0 not the end,, trick here: more than one words!!!
    int ch[SIGMA_SIZE];
    int fail,last;
}node[maxn];
#define ch(x,c) node[x].ch[c]
#define fail(x) node[x].fail
#define last(x) node[x].last
#define val(x) node[x].val
int maxnode;//root=0
void insert(char s[])
{
    int lens=strlen(s);
    int pos=0;
    int root=0;
    while(pos<lens)
    {
        int c=idx(s[pos++]);
        if(!ch(root,c)) ch(root,c)=++maxnode;
        root=ch(root,c);
    }
    val(root)++;
}
queue <int> que;
void get_fail()
{
    fail(0)=0;
    for(int i=0;i<SIGMA_SIZE;i++)
        if(ch(0,i)) { que.push(ch(0,i));fail(0)=last(0)=0; }
    while(!que.empty())
    {
        int u=que.front();que.pop();
        for(int i=0;i<SIGMA_SIZE;i++)
        {
            int v=ch(u,i);
            if(!v) continue;
            que.push(v);
            int t=fail(u);
            while(t && !ch(t,i)) t=fail(t);
            fail(v)=ch(t,i);last(v)=val(fail(v))?fail(v):last(fail(v));
        }
    }
}
inline int count(int root)
{
    if(!root) return 0;
    int ret=count(last(root))+val(root);
    val(root)=0;
    return ret;
}
int find(char s[])
{
    int ret=0;
    int lens=strlen(s);
    int root=0;
    for(int i=0;i<lens;i++)
    {
        int c=idx(s[i]);
        while(root&&!ch(root,c)) root=fail(root);
        root=ch(root,c);//!!!
        if(val(root)) ret+=count(root);
        else ret+=count(last(root));
    }
    return ret;
}
char s[maxlen];
int n;
inline void debug()
{
    cout<<"*/***********************************/*"<<endl;
    for(int i=0;i<=maxnode;i++)
    {
        printf("node %d:\nval=%2d fail=%2d last=%2d\n",i,node[i].val,node[i].fail,node[i].last);
        for(int j=0;j<SIGMA_SIZE;j++) printf("%2c ",j+'a');puts("");
        for(int j=0;j<SIGMA_SIZE;j++) printf("%2d ",j+1);puts("");
        for(int j=0;j<SIGMA_SIZE;j++) printf("%2d ",node[i].ch[j]);puts("");
        printf("*************\n");  
    }
    cout<<"*/***********************************/*"<<endl;
}
void init()
{
    memset(node,0,sizeof(node));maxnode=0;
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%s",s),insert(s);
    scanf("%s",s);
}
int main()
{
    #ifdef Local
    freopen("aho.in","r",stdin);
    freopen("aho.out","w",stdout);
    #endif
    int cas;
    scanf("%d",&cas);
    while(cas--)
    {
        init();
        get_fail();
//      debug();
        printf("%d\n",find(s));
    }
    return 0;
}

不带fail优化,转移一视同仁

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<iomanip>
#include<ctime>
#include<climits>
#include<cctype>
#include<algorithm>
#ifdef WIN32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=10000*50+5;
const int maxlen=1000005;
const int SIGMA_SIZE=26;
inline int idx(char c) { return c-'a'; }
struct Node
{
    int val;
    int ch[SIGMA_SIZE];
    int fail,last;
}node[maxn];
#define val(x) node[x].val
#define fail(x) node[x].fail
#define last(x) node[x].last
#define ch(x,i) node[x].ch[i]
int maxnode; // root=0
void insert(char s[])
{
    int lens=strlen(s);
    int pos=0;
    int root=0;
    while(pos^lens)
    {
        int c=idx(s[pos]);
        if(!ch(root,c)) ch(root,c) = ++maxnode;
        root = ch(root,c);
        pos++;
    }
    val(root)++;
}
void build_fail()
{
    queue <int> que;
    for(int i=0;i<SIGMA_SIZE;i++)
        if(ch(0,i)) que.push(ch(0,i));
    while(!que.empty())
    {
        int u=que.front();que.pop();
        for(int i=0;i<SIGMA_SIZE;i++)
        {
            int v = ch(u,i);
            if(!v) { ch(u,i) = ch(fail(u),i); continue; }
            que.push(v);
            int t = fail(u);
            while(t && !ch(t,i)) t = fail(t);
            fail(v) = ch(t,i);
            last(v) = val(fail(v))? fail(v) : last(fail(v));
        }
    }
}
int print(int root)
{
    if(!root) return 0;
    int tmp = val(root); // remember to delete those searched!!
    val(root) = 0;
    return tmp + print(last(root));
}
int find(char s[])
{
    int ret = 0;
    int lens = strlen(s);
    int root = 0;
    int pos = 0;
    while(pos ^ lens)
    {
        int c = idx(s[pos]);
        root = ch(root,c);
        if(val(root)) ret += print(root);
        else if(last(root)) ret += print(last(root));
        pos++;
    }
    return ret;
}
char s[maxlen];
int n;
inline void init()
{
    memset(node,0,sizeof(node));
    maxnode = 0;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%s",s);
        insert(s);
    }
}
int main()
{
    freopen("aho.in","r",stdin);
    freopen("aho.out","w",stdout);
    int query;
    scanf("%d",&query);
    while(query--)
    {
        init();
        build_fail();
        scanf("%s",s);
        printf("%d\n",find(s));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值