hdu 2896

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
bool cmp(int a,int b)
{
    return a<b;
}
struct node
{
    node *fail;
    node *next[95];
    int id;
    node()
    {
        id=0;//注意初始化
        fail=NULL;
        memset(next,0,sizeof(next));
    }
}*q[200005];
node *root;
int head,tail,num,a[600],mark[600];
void insert(char *str,int id)
{
    int i;
    node *p=root;
    for(i=0;str[i]!='\0';i++)
    {
        int len=str[i]-32;
        if(p->next[len]==NULL)
            p->next[len]=new node();
        p=p->next[len];
    }
    p->id=id;
}
void build_ac_automation()
{
    int i;
    q[head++]=root;
    root->fail=NULL;
    while(head!=tail)
    {
        node *temp=q[tail++];
        node *p=NULL;
        for(i=0;i<95;i++)
        {
            if(temp->next[i]!=NULL)
            {
                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];
            }
        }
    }
}
int query(char *str)
{
    int i=0;
    node *p=root;
    memset(mark,0,sizeof(mark));
    while(str[i])
    {
        int len=str[i]-32;
        while(p->next[len]==NULL&&p!=root)
            p=p->fail;
        p=p->next[len];
        p=(p==NULL)?root:p;
        node *temp=p;
        while(temp!=root&&!mark[temp->id])
        {
            if(temp->id!=0)
                a[num++]=temp->id;
            mark[temp->id]=1;
            temp=temp->fail;
        }
        i++;
    }
    return num;
}
int main()
{
    int n,m,sum,i,ans,j;
    char str[20005];
    while(scanf("%d",&n)!=EOF)
    {
        root=new node();
        for(i=1;i<=n;i++)
        {
            scanf("%s",str);
            insert(str,i);
        }
        head=tail=0;
        build_ac_automation();
        scanf("%d",&m);
        sum=0;
        for(i=1;i<=m;i++)
        {
            scanf("%s",str);
            num=0;
            ans=query(str);
            if(ans!=0)
            {
                sum++;
                sort(a,a+num,cmp);
                printf("web %d:",i);
                for(j=0;j<ans;j++)
                    printf(" %d",a[j]);
                printf("\n");
            }
        }
        printf("total: %d\n",sum);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值