hdu3065 病毒侵袭持续中【AC自动机】

时间:2023-03-09 07:12:29
hdu3065 病毒侵袭持续中【AC自动机】

病毒侵袭持续中

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 19553    Accepted Submission(s): 6409

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
Hint

Hit:
题目描述中没有被提及的所有情况都应该进行考虑。比如两个病毒特征码可能有相互包含或者有重叠的特征码段。
计数策略也可一定程度上从Sample中推测。

Source
Recommend
lcy   |   We have carefully selected several similar problems for you:  2243 2825 3247 3341 2296 

题意:

还是n个病毒,现在是1个文本串。统计模式串在文本串中出现的次数。

思路:

这个不是统计个数,就不需要vis了。同样要注意文本串中有可能有除了字母以外的字符,son还是要开了130

 #include <iostream>
#include <set>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
//#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define inf 0x7f7f7f7f int m, n;
const int maxn = ;
const int maxlen = 2e6 + ; struct virus{
char str[];
int id;
}vir[maxn];
struct tree{
int fail;
int son[];
int ed;
//bool vis;
}AC[maxlen];
int tot = ;
char s[maxlen]; void build(char s[], int id)
{
int len = strlen(s);
int now = ;
for(int i = ; i < len; i++){
if(AC[now].son[s[i]] == ){
AC[now].son[s[i]] = ++tot;
}
now = AC[now].son[s[i]];
}
AC[now].ed = id;
} void get_fail()
{
queue<int>que;
for(int i = ; i < ; i++){
if(AC[].son[i] != ){
AC[AC[].son[i]].fail = ;
que.push(AC[].son[i]);
}
}
while(!que.empty()){
int u = que.front();
que.pop();
for(int i = ; i < ; i++){
if(AC[u].son[i] != ){
AC[AC[u].son[i]].fail = AC[AC[u].fail].son[i];
que.push(AC[u].son[i]);
}
else{
AC[u].son[i] = AC[AC[u].fail].son[i];
}
}
}
} int cnt[maxn];
void AC_query(char s[])
{
/*for(int i = 0; i <= tot; i++){
AC[i].vis = false;
}*/
int len = strlen(s);
int now = ;
for(int i = ; i < len; i++){
now = AC[now].son[s[i]];
for(int t = now; t; t = AC[t].fail){
if(AC[t].ed != ){
cnt[vir[AC[t].ed].id]++;
//AC[t].vis = true;
}
}
}
} int main()
{
while(scanf("%d", &n) != EOF){
for(int i = ; i <= tot; i++){
AC[i].fail = ;
//AC[i].vis = false;
AC[i].ed = ;
for(int j = ; j < ; j++){
AC[i].son[j] = ;
}
}
tot = ;
for(int i = ; i <= n; i++){
cnt[i] = ;
scanf("%s", vir[i].str);
vir[i].id = i;
build(vir[i].str, vir[i].id);
}
AC[].fail = ;
get_fail();
getchar();
gets(s);
AC_query(s);
for(int i = ; i <= n; i++){
if(cnt[i]){
printf("%s: %d\n", vir[i].str, cnt[vir[i].id]);
}
}
}
return ;
}