您的位置:首页 > 其它

HDU 3065(ac自动机)

2013-07-22 18:42 330 查看
病毒侵袭持续中

Problem Description

小t非常感谢大家帮忙解决了他的上一个问题。然而病毒侵袭持续中。在小t的不懈努力下,他发现了网路中的“万恶之源”。这是一个庞大的病毒网站,他有着好多好多的病毒,但是这个网站包含的病毒很奇怪,这些病毒的特征码很短,而且只包含“英文大写字符”。当然小t好想好想为民除害,但是小t从来不打没有准备的战争。知己知彼,百战不殆,小t首先要做的是知道这个病毒网站特征:包含多少不同的病毒,每种病毒出现了多少次。大家能再帮帮他吗?

 

Input

第一行,一个整数N(1<=N<=1000),表示病毒特征码的个数。

接下来N行,每行表示一个病毒特征码,特征码字符串长度在1—50之间,并且只包含“英文大写字符”。任意两个病毒特征码,不会完全相同。

在这之后一行,表示“万恶之源”网站源码,源码字符串长度在2000000之内。字符串中字符都是ASCII码可见字符(不包括回车)。

 

Output

按以下格式每行一个,输出每个病毒出现次数。未出现的病毒不需要输出。

病毒特征码: 出现次数

冒号后有一个空格,按病毒特征码的输入顺序进行输出。

 

Sample Input

3

AA

BB

CC

ooxxCC%dAAAoen....END

 

Sample Output

AA: 2

CC: 1

 

简单的ac自动机。

 

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
struct Tree{
int ch[26];
int fail;
int asd;
}tree[2000050];
char ss[1005][55],str[2000005];
int tot,f[1005],n;
void tire_insert(int x){
int l,t,root,i;
l=strlen(ss[x]);
t=0;root=1;
while(t<l){
if(tree[root].ch[ss[x][t]-'A']!=0){
root=tree[root].ch[ss[x][t]-'A'];
t++;
}
else {
tot++;
tree[root].ch[ss[x][t]-'A']=tot;
root=tot;
for(i=0;i<=25;i++)
tree[root].ch[i]=0;
tree[root].fail=0;
tree[root].asd=0;
t++;
}
//printf("%d ",root);
}
//printf("\n");
tree[root].asd=x;
return ;
}
void ac_build(){
int s,w,i,e;
queue<int>q;
q.push(1);
int t=0;
while(!q.empty()){
s=q.front();
q.pop();
for(i=0;i<=25;i++)
if(tree[s].ch[i]!=0){
w=tree[s].ch[i];
if(s==1)tree[w].fail=1;
else{
e=tree[s].fail;
while(tree[e].ch[i]==0&&e!=0)e=tree[e].fail;
if(e==0)tree[w].fail=1;
else tree[w].fail=tree[e].ch[i];
}
q.push(w);
}

}
//printf("%d \n",tree[3].fail);
return ;
}
void ac_query(){
int l,t,root,e,q;
l=strlen(str);
t=0;root=1;
while(t<l){
while((str[t]<'A'||str[t]>'Z')&&t<l){root=1;t++;}
if(t>=l)break;
if(tree[root].ch[str[t]-'A']!=0){
root=tree[root].ch[str[t]-'A'];
t++;
}
else {
e=tree[root].fail;
while(tree[e].ch[str[t]-'A']==0&&e!=0)e=tree[e].fail;
if(e==0)root=1;
else root=tree[e].ch[str[t]-'A'];
t++;
}
// printf("%d ",root);
q=root;
while(q!=0){
f[tree[q].asd]++;
q=tree[q].fail;
}
}
return ;
}
void work(){
int i;
ac_build();
ac_query();
for(i=1;i<=n;i++)
if(f[i]){
printf("%s: %d\n",ss[i],f[i]);
}
return ;
}
void init(){
int i;
while(scanf("%d",&n)!=EOF){
tot=1;
for(i=0;i<=25;i++)
tree[1].ch[i]=0;
tree[1].fail=0;
tree[1].asd=0;
for(i=1;i<=n;i++){
f[i]=0;
scanf("%s",ss[i]);
tire_insert(i);
}
scanf("%s",str);
work();
}
return ;
}
int main(){
init();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu