病毒侵袭持续中
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 1 Accepted Submission(s) : 1
Problem Description
小t非常感谢大家帮忙解决了他的上一个问题。然而病毒侵袭持续中。在小t的不懈努力下,他发现了网路中的“万恶之源”。这是一个庞大的病毒网站,他有着好多好多的病毒,但是这个网站包含的病毒很奇怪,这些病毒的特征码很短,而且只包含“英文大写字符”。当然小t好想好想为民除害,但是小t从来不打没有准备的战争。知己知彼,百战不殆,小t首先要做的是知道这个病毒网站特征:包含多少不同的病毒,每种病毒出现了多少次。大家能再帮帮他吗?
Input
第一行,一个整数N(1<=N<=1000),表示病毒特征码的个数。
接下来N行,每行表示一个病毒特征码,特征码字符串长度在1—50之间,并且只包含“英文大写字符”。任意两个病毒特征码,不会完全相同。
在这之后一行,表示“万恶之源”网站源码,源码字符串长度在2000000之内。字符串中字符都是ASCII码可见字符(不包括回车)。
接下来N行,每行表示一个病毒特征码,特征码字符串长度在1—50之间,并且只包含“英文大写字符”。任意两个病毒特征码,不会完全相同。
在这之后一行,表示“万恶之源”网站源码,源码字符串长度在2000000之内。字符串中字符都是ASCII码可见字符(不包括回车)。
Output
按以下格式每行一个,输出每个病毒出现次数。未出现的病毒不需要输出。
病毒特征码: 出现次数
冒号后有一个空格,按病毒特征码的输入顺序进行输出。
病毒特征码: 出现次数
冒号后有一个空格,按病毒特征码的输入顺序进行输出。
Sample Input
3 AA BB CC ooxxCC%dAAAoen....END
Sample Output
AA: 2 CC: 1Hint
#include<cstdio>
#include<string.h>
#include<iostream>
#include<queue>
#include<algorithm>
#define kind 30
using namespace std;
char st[1100][60];
char st1[2000009];
int vis[1100];
struct node
{
int pox;
struct node *fail;
struct node *next[kind];
node()
{
for(int i=0; i<kind; i++)
{
next[i]=NULL;
pox=-1;
}
}
};
void buildTree(char te[],struct node *root,int s)
{
struct node *tem=root;
int len=strlen(te);
for(int i=0; i<len; i++)
{
int index=te[i]-'A';
if(tem->next[index]==NULL)
tem->next[index]=new node();
tem=tem->next[index];
}
tem->pox=s;
}
void BFS(struct node *root)
{
queue<struct node*>q;
struct node *tem,*p;
root->fail=NULL;
q.push(root);
while(!q.empty())
{
tem=q.front();
q.pop();
for(int i=0; i<kind; i++)
{
if(tem->next[i]!=NULL)
{
if(tem==root) tem->next[i]->fail=root;
else
{
p=tem->fail;
while(p!=NULL)
{
if(p->next[i]!=NULL)
{
tem->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL)
tem->next[i]->fail=root;
}
q.push(tem->next[i]);
}
}
}
}
void find(struct node *root)
{
int i = 0, index ;
struct node *p = root ;
int len=strlen(st1);
for(int i=0;i<len;i++)
{
index = st1[i] - 'A' ;
if(index<0||index>=26)
index = 27 ;
while(p->next[index]==NULL && p!=root)
p = p->fail ;
p = p->next[index] ;
p = (p==NULL) ? root : p ;
struct node *temp = p ;
while(temp!=root)
{
if(temp->pox!=-1)
vis[temp->pox] ++ ;
temp = temp->fail ;
}
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
memset(vis,0,sizeof(vis));
struct node *root=new node();
for(int i=0; i<n; i++)
{
scanf("%s",st[i]);
buildTree(st[i],root,i);
}
BFS(root);
scanf("%s",st1);
find(root);
for(int i=0;i<n;i++)
if(vis[i])
printf("%s: %d\n",st[i],vis[i]);
}
return 0;
}