hdu 2896 病毒侵染 (AC自动机)

 不知道是我理解能力弱还是题意不清,最后的输出结果坑了我好长时间。这个题不要求去重的,给个数据吧

Sample Input
1
ab
1
abab

Sample Output
web 1: 1 1
total: 1
#include <iostream>
#include <cctype>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstdio>
#include <cstdlib>
#define inf 0x3f3f3f3f
#define LL long long 
#define maxn 1000005
#define For(i, a, b) for(int i = a; i <= b; i++)
#define Forx(i, a, b) for(int i = b; i >= a; i--)
#define Testin freopen("ztest.txt", "r", stdin) 
#define Ansout freopen("zans.txt","w", stdout)
#define Memset(a) memset(a, 0, sizeof(a))
using namespace std;

struct Node{
	int count;
	Node* fail;
	Node* next[131];
};
queue<Node*> que;
int ans[10000];
char str[1000000];

void insert(string str, Node* root, int k){
	Node* p = root;
	For(i, 0, str.size()-1){
		int id = str[i];
		if(p->next[id] == NULL){
			Node* ne = (Node*) malloc (sizeof(Node));
			ne->fail = NULL;
			ne->count = -1;
			For(j, 0, 130)
				ne->next[j] = NULL;
			p->next[id] = ne;
		}
		p = p->next[id];
	}
	p->count = k;
}

void build_ac(Node* root){
	Node* p = root;
	que.push(p);
	while(!que.empty()){
		Node* fr = que.front();
		que.pop();
		For(i, 0, 130){
			
			if(fr->next[i] != NULL){
				
				if(fr == root)
					fr->next[i]->fail = root;
				else{
					Node* par = fr->fail;
					while(par != NULL){
						if(par->next[i] != NULL){
							fr->next[i]->fail = par->next[i];
							break;
						}
						par = par->fail;
					}
					if(par == NULL)
						fr->next[i]->fail = root;
				}
				que.push(fr->next[i]);
			}
		}
	}
}

int query(string text, Node* root){
	int anss = 0;
	Node* p = root;
	For(i, 0, text.size()-1){
		int id = text[i];
		while(p != NULL && p->next[id] == NULL)
			p = p->fail;
		if(p != NULL)
			p = p->next[id];
		else
			p = root;
		Node* temp = p;
		while(temp != root){
			if(temp->count >= 0){
				ans[anss++] = temp->count;
			}
			else
				break;
			temp = temp->fail;
		}
	}
	return anss;
}
			
int main(){
	//Testin;
	int n;
	while(scanf("%d", &n) == 1){
	Node* root = (Node*) malloc (sizeof(Node));
	For(i, 0, 130)
		root->next[i] = 0;
	root->fail = NULL;
	For(i, 1, n){
		cin >> str;
		insert(str, root, i);
	}
	build_ac(root);
	scanf("%d", &n);
	int sum = 0;
	For(i, 1, n){
		Memset(ans);
		cin >> str;
		int num = query(str, root);
		if(num){
			sum++;
			printf("web %d:", i);
			sort(ans, ans+num);
			For(j, 0, num-1)	printf(" %d", ans[j]);
			printf("\n");
		}
	}
	printf("total: %d\n",sum);}
	return 0;
}
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值