HDU 2896

EASY题

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <string.h>
#include <queue>
#include <cmath>
#include <vector>

using namespace std;
const int dictsize=130;
const int QN=400000;
bool nvr[505];
int n,m,ans_cnt,qf,ql;

struct Node {
	Node *fail;
	Node *next[dictsize];
	int count;
	Node (){
		for(int i=0;i<dictsize;i++)
		next[i]=NULL;
		fail=NULL;
		count=0;
	}
	void initial(){
		for(int i=0;i<dictsize;i++)
		next[i]=NULL;
		fail=NULL;
		count=0;
	}
};
Node *que[QN],*root;
char inser[210],str[10010];


void Insert_Trie(int counts){
	Node *p=root;
	int i=0,index;
	while(inser[i]){
		index=inser[i]-31;
		while(!p->next[index]) p->next[index]=new Node();
		p=p->next[index];
		i++;
	}
	p->count=counts;
}

void set_fail(){
	int i=0;
	qf=ql=0;
	root->fail=NULL;
	que[ql++]=root;
	Node *tmp,*p;
	while(qf!=ql){
		tmp=que[qf++];
		p=NULL;
		for(i=0;i<=128;i++){
			if(tmp->next[i]){
				if(tmp==root) tmp->next[i]->fail=root;
				else{
					p=tmp->fail;
					while(p){
						if(p->next[i]){
							tmp->next[i]->fail=p->next[i];
							break;
						}
						p=p->fail;
					}
					if(!p) tmp->next[i]->fail=root;
				}
				que[ql++]=tmp->next[i];
			}
		}
	}
}


int query(){
	int i=0,index,cnt=0;
	Node *p=root,*tmp;
	while(str[i]){
		index=str[i]-31;
		while(!p->next[index]&&p!=root) p=p->fail;
		p=p->next[index];
		p=p?p:root;
		tmp=p;
		while(tmp!=root){
			if(tmp->count>0){
				if(!nvr[tmp->count]){
					nvr[tmp->count]=true;
					cnt++;
				}
			}
			tmp=tmp->fail;
		}
		i++;
	}
	return cnt;
}

int main(){
	while(scanf("%d",&n)!=EOF){
		root=new Node();
		for(int i=1;i<=n;i++){
			scanf("%s",inser);
			Insert_Trie(i);
		}
		ans_cnt=0;
		set_fail();
		scanf("%d",&m);
		for(int i=1;i<=m;i++){
			memset(nvr,false,sizeof(nvr));
			scanf("%s",str);
			if(query()>0){
				ans_cnt++;
				printf("web %d:",i);
				for(int k=0;k<=500;k++){
					if(nvr[k])
					printf(" %d",k);
				}
				printf("\n");
			}
		}
		printf("total: %d\n",ans_cnt);
	}
	return 0;
}

  

posted @ 2015-03-01 09:54  chenjunjie1994  阅读(166)  评论(0编辑  收藏  举报