hdu 3065

本文详细介绍了如何使用C++实现字符串匹配算法,包括AC自动机的构建与查询过程,通过实例展示了该算法在解决实际问题中的高效性和实用性。
#include<stdio.h>
#include<string.h>
int cnt[1005];
char str[1005][100],s[2000005];
struct node
{
    node *fail;
    node *next[33];
    int id;
    node()
    {
        id=0;
        fail=NULL;
        memset(next,0,sizeof(next));
    }
}*q[50005];
node *root;
void insert(char *str,int id)
{
    int i;
    node *p=root;
    for(i=0; str[i]!='\0'; i++)
    {
        int len=str[i]-'A';
        if(p->next[len]==NULL)
            p->next[len]=new node();
        p=p->next[len];
    }
    p->id=id;
}
void build_ac_automation()
{
    int head=0,tail=0,i;
    q[head++]=root;
    root->fail=NULL;
    while(head!=tail)
    {
        node *temp=q[tail++];
        node *p=NULL;
        for(i=0; i<32; i++)
        {
            if(temp->next[i]!=0)
            {
                if(temp==root)
                    temp->next[i]->fail=root;
                else
                {
                    p=temp->fail;
                    while(p!=NULL)
                    {
                        if(p->next[i]!=NULL)
                        {
                            temp->next[i]->fail=p->next[i];
                            break;
                        }
                        p=p->fail;
                    }
                    if(p==NULL)
                        temp->next[i]->fail=root;
                }
                q[head++]=temp->next[i];
            }
        }
    }
}
void query(char *str)
{
    int i=0,n;
    node *p=root;
    while(str[i])
    {
        if(str[i]>='A'&&str[i]<='Z')
        {
            n=str[i]-'A';
            while(p->next[n]==NULL&&p!=root)
                p=p->fail;
            p=p->next[n];
            p=(p==NULL)?root:p;
            node *temp=p;
            while(temp!=root&&temp->id>0)
            {
                cnt[temp->id]++;
                temp=temp->fail;
            }
        }
        else
            p=root;
        i++;
    }
}
int main()
{
    int i,n;
    while(scanf("%d",&n)!=EOF)
    {
        root=new node();
        for(i=1; i<=n; i++)
        {
            scanf("%s",str[i]);
            insert(str[i],i);
        }
        build_ac_automation();
        memset(cnt,0,sizeof(cnt));
        scanf("%s",s);
        query(s);
        for(i=1; i<=n; i++)
            if(cnt[i]!=0)
                printf("%s: %d\n",str[i],cnt[i]);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值