题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3065
3 AA BB CC ooxxCC%dAAAoen....END
AA: 2 CC: 1HintHit: 题目描述中没有被提及的所有情况都应该进行考虑。比如两个病毒特征码可能有相互包含或者有重叠的特征码段。 计数策略也可一定程度上从Sample中推测。
代码如下:
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
#include <string>
using namespace std;
char ss[1017][57];
int ans[1017];
struct Trie
{
int next[500010][128],fail[500010],end[500010];
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]);
}
}
}
void query(char buf[], int n)
{
memset(ans,0,sizeof(ans));
int len = strlen(buf);
int now = root;
for(int i = 0; i < len; i++)
{
now = next[now][buf[i]];
int temp = now;
while( temp != root )
{
//res += end[temp];
//printf("temp:%d end[temp]:%d\n",temp,end[temp]);
if(end[temp] != -1)
{
ans[end[temp]]++;
}
//end[temp] = 0;
temp = fail[temp];
}
}
}
};
char buf[2000010];
Trie ac;
int main()
{
int t, n;
while(~scanf("%d",&n))
{
ac.init();
for(int i = 0; i < n; i++)
{
scanf("%s",ss[i]);
ac.insert(ss[i],i);
}
ac.build();//fail
scanf("%s",buf);
ac.query(buf, n);
for(int i = 0; i < n; i++)
{
if(ans[i])
{
printf("%s: %d\n",ss[i],ans[i]);
}
}
}
return 0;
}
原文地址:http://blog.csdn.net/u012860063/article/details/44465401