病毒侵袭持续中
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 8183 Accepted Submission(s): 2858
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: 1HintHit: 题目描述中没有被提及的所有情况都应该进行考虑。比如两个病毒特征码可能有相互包含或者有重叠的特征码段。 计数策略也可一定程度上从Sample中推测。
Source
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=30;
struct Trie{
Trie *fail; //失败指针
Trie *next[N]; //Tire每个节点的26个子节点(最多26个字母)
int count; //是否为该单词的最后一个节点
int word_id;
Trie(){ //构造函数初始化
fail=NULL;
count=0;
word_id=0;
memset(next,NULL,sizeof(next));
}
}*q[500010]; //队列,方便用于bfs构造失败指针
int num[1010];
char word[1010][55]; //输入的单词
char str[2000010]; //模式串
int head,tail; //队列的头尾指
void Insert(char *str,Trie *Root,int n){
Trie *loc=Root;
int i=0;
while(str[i]!='\0'){
int id=str[i]-'A';
if(loc->next[id]==NULL)
loc->next[id]=new Trie();
loc=loc->next[id];
i++;
}
loc->count++;
loc->word_id=n;
}
void AC_automation(Trie *Root){
Root->fail=NULL;
q[head++]=Root;
Trie *cur,*tmp;
while(head!=tail){
cur=q[tail++];
tmp=NULL;
for(int i=0;i<N;i++){
if(cur->next[i]!=NULL){
if(cur==Root)
cur->next[i]->fail=Root;
else{
tmp=cur->fail;
while(tmp!=NULL){
if(tmp->next[i]!=NULL){
cur->next[i]->fail=tmp->next[i];
break;
}
tmp=tmp->fail;
}
if(tmp==NULL)
cur->next[i]->fail=Root;
}
q[head++]=cur->next[i];
}
}
}
}
int query(Trie *Root){
int i=0,cnt=0;
Trie *loc=Root,*tmp;
while(str[i]!='\0'){
int id=str[i]-'A';
if(id<0 || id>26)
id=27;
while(loc->next[id]==NULL && loc!=Root)
loc=loc->fail;
loc=loc->next[id];
loc=(loc==NULL)?Root:loc;
tmp=loc;
while(tmp!=Root){
if(tmp->word_id!=-1)
{
num[tmp->word_id]++;
cnt+=tmp->count;
}
// tmp->count=-1;
tmp=tmp->fail;
}
i++;
}
return cnt;
}
/*
abc
abcabcabc
*/
int main(){
//freopen("input.txt","r",stdin);
int i,n;
while(scanf("%d%*c",&n)!=EOF)
{
memset(num,0,sizeof(num));
head=tail=0;
Trie *Root=new Trie();
for(i=1;i<=n;i++){
scanf("%s",&word[i]);
Insert(word[i],Root,i);
}
AC_automation(Root);
scanf("%s",str);
query(Root);
for(i=1;i<=n;i++)
{
if(num[i])
{
printf("%s: %d\n",word[i],num[i]);
}
}
}
return 0;
}