病毒侵袭持续中
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 15706 Accepted Submission(s): 5331
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
Recommend
lcy
解题思路:ac自动机
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cctype>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
char ch[2000010], s[1009][55];
struct Trie
{
int next[50010][128], fail[500010], flag[500010];
int root, tot;
int vis[50010];
int newnode()
{
for (int i = 0; i < 128; i++) next[tot][i] = -1;
flag[tot++] = 0;
return tot - 1;
}
void init()
{
tot = 0;
root = newnode();
}
void insert(char ch[], int id)
{
int k = root;
for (int i = 0; ch[i]; i++)
{
if (next[k][ch[i]] == -1) next[k][ch[i]] = newnode();
k = next[k][ch[i]];
}
flag[k] = id;
}
void build()
{
queue<int>q;
fail[root] = root;
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 pre = q.front();
q.pop();
for (int i = 0; i < 128; i++)
{
if (next[pre][i] == -1) next[pre][i] = next[fail[pre]][i];
else
{
fail[next[pre][i]] = next[fail[pre]][i];
q.push(next[pre][i]);
}
}
}
}
void query(char ch[])
{
memset(vis, 0, sizeof vis);
int k = root;
for (int i = 0; ch[i]; i++)
{
k = next[k][ch[i]];
int temp = k;
while (temp != root)
{
vis[flag[temp]]++;
temp = fail[temp];
}
}
}
void debug()
{
for (int i = 0; i < tot; i++)
{
printf("id = %3d,fail = %3d,end = %3d,chi = [", i, fail[i], flag[i]);
for (int j = 0; j < 26; j++) printf("%2d", next[i][j]);
printf("]\n");
}
}
}ac;
int main()
{
int n;
while (~scanf("%d", &n))
{
ac.init();
for (int i = 1; i <= n; i++)
{
scanf("%s", s[i]);
ac.insert(s[i], i);
}
ac.build();
scanf("%s", ch);
ac.query(ch);
for (int i = 1; i <= n; i++)
if (ac.vis[i]) printf("%s: %d\n", s[i], ac.vis[i]);
}
return 0;
}