题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2896
3 aaa bbb ccc 2 aaabbbccc bbaacc
web 1: 1 2 3 total: 1
代码如下:
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
int f[520]; //标记当前某个网站是否包含某个病毒
int flag = 0;
struct Trie
{
int next[500*210][128],fail[500*210],end[500*210];
int root,L;
int newnode()
{
for(int i = 0; i < 128; i++)
next[L][i] = -1;
end[L++] = -1;
return L-1;
}
void init()
{
L = 0;
root = newnode();
}
void insert(char buf[], int id)
{
int len = strlen(buf);
int now = root;
for(int i = 0; i < len; i++)
{
if(next[now][buf[i]] == -1)
next[now][buf[i]] = newnode();
now = next[now][buf[i]];
}
end[now] = id;
}
void build()
{
queue<int>Q;
fail[root] = root;
for(int i = 0; i < 128; i++)
if(next[root][i] == -1)
next[root][i] = root;
else
{
fail[next[root][i]] = root;
Q.push(next[root][i]);
}
while(!Q.empty())
{
int now = Q.front();
Q.pop();
for(int i = 0; i < 128; i++)
if(next[now][i] == -1)
next[now][i] = next[fail[now]][i];
else
{
fail[next[now][i]]=next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
int query(char buf[], int id)
{
int len = strlen(buf);
int now = root;
int mark = 0;
for(int i = 0; i < len; i++)
{
now = next[now][buf[i]];
int temp = now;
while( temp != root )
{
if(end[temp] != -1)
{
f[end[temp]] = 1;
mark = 1;
}
temp = fail[temp];
}
}
if(!mark)
return 0;
return 1;
}
};
char buf[10010];
Trie ac;
int main()
{
int n, m;
while(~scanf("%d",&n))
{
ac.init();
for(int i = 1; i <= n; i++)
{
scanf("%s",buf);
ac.insert(buf, i);
}
ac.build();//fail
int ans = 0;
scanf("%d",&m);
for(int i = 1; i <= m; i++)
{
memset(f, 0, sizeof(f));
scanf("%s",buf);
int flag = ac.query(buf, i);
if(!flag)
{
continue;
}
printf("web %d:",i);
for(int j = 1; j <= n; j++)
{
if(f[j])
{
printf(" %d",j);
}
}
printf("\n");
ans++;
}
printf("total: %d\n",ans);
}
return 0;
}
原文地址:http://blog.csdn.net/u012860063/article/details/44463397