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

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2896

注意字符集大小。。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue> 
#include<vector>
using namespace std;
typedef long long ll;

const int maxn = 100010;

int n, m, tot = 0, rt = 0;
vector<int> ans; 

char s[10010];

struct Node{
	int son[130], fail, id, vis;
}t[maxn];

void insert(int num){
	int p = 0;
	int len = strlen(s);
	for(int i = 0 ; i < len ; ++i){
		int c = s[i];
		if(!t[p].son[c]){
			t[p].son[c] = ++tot;
		}
		p = t[p].son[c];
	}
	t[p].id = num;
}

queue<int> q;

void build(){
	for(int i = 0 ; i <= 128 ; ++i){
		if(t[0].son[i]) q.push(t[0].son[i]);
	}
	
	while(!q.empty()){
		int u = q.front(); q.pop();
		for(int i = 0 ; i <= 128 ; ++i){
			if(t[u].son[i]){
				t[t[u].son[i]].fail = t[t[u].fail].son[i];
				q.push(t[u].son[i]);
			} else{
				t[u].son[i] = t[t[u].fail].son[i];
			}
		}
	}
}

void query(){
	int len = strlen(s);
	int p = 0;
	for(int i = 0 ; i < len ; ++i){
		p = t[p].son[s[i]];
//		printf("%d %d\n", p, t[p].id); 
		for(int j = p ; j && !t[j].vis ; j = t[j].fail) {//
			if(t[j].id) ans.push_back(t[j].id);
			t[j].vis = 1;
		}
	} 
}

ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }

int main(){
	n = read();
	for(int i = 1 ; i <= n ; ++i){
		scanf("%s", s);
		insert(i);
	}
	
	build();
	
	m = read();
	int cnt = 0;
	for(int i = 1 ; i <= m ; ++i){
		scanf("%s", s);
		for(int j = 0 ; j <= tot ; ++j) t[j].vis = 0;
		query();
	
		if(ans.size()) {
			++cnt;
			printf("web %d:", i);
			sort(ans.begin(), ans.end());
			for(int j = 0 ; j < ans.size() ; ++j){
				printf(" %d", ans[j]);
			}
			printf("\n");
		}
		ans.clear();
	} 
	printf("total: %d\n", cnt);
	
	return 0;
}
posted @ 2020-12-25 20:30  Tartarus_li  阅读(60)  评论(0编辑  收藏  举报