您的位置:首页 > 其它

HDU 3065 病毒侵袭持续中 (AC自动机)

2017-08-18 08:22 369 查看
思路:

也是个ac自动机裸题

给每个节点维护编号 和数量就好。 

因为一个节点可能会重复匹配一个病毒多次,  所以不能清空维护的数量。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

const int maxn = 50000 + 10;
int ans[maxn];
struct Trie{
int L, root;
int next[maxn][128];
int fail[maxn];
int num[maxn];
int flag[maxn];

void init(){
L = 0;
root = newnode();
}
int newnode(){
for (int i = 0; i < 128; ++i){
next[L][i] = -1;
}
num[L] = 0;
flag[L] = -1;
return L++;
}

void insert(char* s,int f){
int len = strlen(s);
int nod = root;
for (int i = 0; i < len; ++i){

int id = s[i];
if (next[nod][id] == -1){
next[nod][id] = newnode();
}
nod = next[nod][id];
}
num[nod]++;
flag[nod] = f;
}

void build(){
queue<int>q;
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 u = q.front(); q.pop();
for (int i = 0; i < 128; ++i){

if (next[u][i] == -1){
next[u][i] = next[fail[u] ][i];
}
else {
fail[next[u][i] ] = next[fail[u] ][i];
q.push(next[u][i]);
}
}
}

}

void query(char* s){
int len = strlen(s);
int nod = root;
for (int i = 0; i < len; ++i){
int id = s[i];
nod = next[nod][id];

int tmp = nod;

while(tmp != root){
if (flag[tmp] != -1){
ans[flag[tmp]-1] += num[tmp];
// num[tmp] = 0;
}
tmp = fail[tmp];
}

}

}

}ac;
char s[maxn][55];
char word[2000000 + 10];
int main(){
int n;
while(~scanf("%d", &n)){
ac.init();
for (int i = 0; i < n; ++i){
scanf("%s", s[i]);
ac.insert(s[i], i +1);
ans[i] = 0;
}
ac.build();
scanf("%s", word);
ac.query(word);
for (int i = 0; i < n; ++i){

if (ans[i]){
printf("%s: %d\n", s[i], ans[i]);
}
}
}
return 0;
}



病毒侵袭持续中

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 14537    Accepted Submission(s): 4954


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

2009 Multi-University Training Contest 16 - Host by NIT

 

Recommend

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

 

Statistic | Submit | Discuss | Note
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: