hdu 2896(AC自动机 简单题练习)

26 篇文章 0 订阅
9 篇文章 0 订阅

http://acm.hdu.edu.cn/showproblem.php?pid=2896


注意输入数据不止有字母。

没什么特别的地方,用来熟悉算法。

#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <queue>
#include<iostream>
using namespace std;
#define N 210
#define M 10100
bool vis[510];
char str[N],page[M];
int total,n_ans;
int ans[10];
struct node{
    int cnt;
    node *next[130];
    node *fail;
    node(){
    fail=NULL;
    cnt=0;
    for(int i=0;i<130;i++) next[i]=NULL;
    }
}*root;
void insert(int num){
    int len,temp;
    node *p=root;
    len=strlen(str);

    for(int i=0;i<len;i++){
        temp=str[i]-31;//printf("1?\n");
        if(p->next[temp]==NULL)
            p->next[temp]=new node();
        p=p->next[temp];
    }
    p->cnt=num;
}//insert
void build_ac(){
    node *p=root,*temp,*cur;
    queue<node*>q;
    q.push(p);
    while(!q.empty()){
        cur=q.front(); q.pop();
        for(int i=0;i<130;i++){
            temp=cur->next[i];
            if(temp!=NULL){
                if(cur==root) temp->fail=root;
                else{
                    p=cur->fail;
                    while(p){
                        if(p->next[i]){temp->fail=p->next[i];break;}
                        p=p->fail;
                    }//while
                    if(!p) temp->fail=root;
                }//else
                q.push(temp);
            }//if
        }//for_26
    }//while
}//build_ac
void query(){
    memset(vis,0,sizeof(vis));
    int len,index;
    len=strlen(page);
    node *p;
    p=root;
    for(int i=0;i<len;i++){
        index=page[i]-31;
        while(!p->next[index]&&p!=root) p=p->fail;
        p=p->next[index];
        if(p==NULL) p=root;
        node *temp=p;
        while(temp->cnt&&temp!=root&&!vis[temp->cnt]){
            vis[temp->cnt]=1;
            ans[n_ans++]=temp->cnt;
            if(n_ans>=3) return;
        }
    }
}//query0
int main(){
    int n,m;
    root = new node();
    scanf("%d",&n);
    getchar();
    for(int i=0;i<n;i++){
        gets(str);

        insert(i+1); //printf("%s\n",str);
    }
    build_ac();
    scanf("%d",&m);
    total=0;
    getchar();
    for(int i=0;i<m;i++){
        gets(page);
        n_ans=0;
        query();
        if(n_ans) {
                sort(ans,ans+n_ans);
                total++;
                printf("web %d:",i+1);
                for(int j=0;j<n_ans;j++) printf(" %d",ans[j]);
                printf("\n");
        }//if
    }//for
    printf("total: %d\n",total);
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值