hdu 3065 病毒侵袭持续中

记得释放内存,不然就会无限Memory Limit Exceeded,表示自己是过来人。

#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
char str1[2000100],str[1005][55];
int a[1005],n,k;
struct node
{
    int cnt,id;
    node *next[100],*fail;
    void init()
    {
        for(int i=0;i<100;i++)
            next[i]=NULL;
        cnt=0;
        fail=NULL;
    }
}*root;
void mt(char *s)
{
    node *p=root;
    int len=strlen(s);
    for(int i=0;i<len;i++)
    {
        int pos=s[i]-' ';
        if(p->next[pos]==NULL)
        {
            p->next[pos]=new node;
            p->next[pos]->init();
            p=p->next[pos];
        }
        else
            p=p->next[pos];
    }
    p->cnt++;
    p->id=++k;
}
void mf()
{
    node *son,*temp,*p=root;
    queue<node *>qu;
    qu.push(p);
    while(!qu.empty())
    {
        temp=qu.front();
        qu.pop();
        for(int i=0;i<100;i++)
        {
            son=temp->next[i];
            if(son)
            {
                if(temp==root)
                    son->fail=root;
                else
                {
                    p=temp->fail;
                    while(p)
                    {
                        if(p->next[i])
                        {
                            son->fail=p->next[i];
                            break;
                        }
                        p=p->fail;
                    }
                    if(!p)
                        son->fail=root;
                }
                qu.push(son);
            }
        }
    }
}
void sm()
{
    int len=strlen(str1);
    node *p=root,*temp;
    for(int i=0;i<len;i++)
    {
        int pos=str1[i]-' ';
        while(!p->next[pos]&&p!=root)
            p=p->fail;
        p=p->next[pos];
        if(!p)
            p=root;
        temp=p;
        while(temp!=root)
        {
            if(temp->cnt)
                a[temp->id]++;
            temp=temp->fail;
        }
    }
    for(int i=1;i<=n;i++)
        if(a[i])
            printf("%s: %d\n",str[i],a[i]);
}
int dt(node* T)
{
    if(T==NULL)
        return 0;
    for(int i=0;i<100;i++)
        if(T->next[i])
            dt(T->next[i]);
    free(T);
    return 0;
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        k=0;
        memset(a,0,sizeof(a));
        root=new node;
        root->init();
        for(int i=1;i<=n;i++)
        {
            scanf("%s",str[i]);
            mt(str[i]);
        }
        mf();
        scanf("%s",str1);
        sm();
        dt(root);
    }
    return 0;
}



      
   

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值