HDU-3065-病毒侵袭持续中(AC自动机)
作者:互联网
链接:
https://vjudge.net/problem/HDU-3065
题意:
小t非常感谢大家帮忙解决了他的上一个问题。然而病毒侵袭持续中。在小t的不懈努力下,他发现了网路中的“万恶之源”。这是一个庞大的病毒网站,他有着好多好多的病毒,但是这个网站包含的病毒很奇怪,这些病毒的特征码很短,而且只包含“英文大写字符”。当然小t好想好想为民除害,但是小t从来不打没有准备的战争。知己知彼,百战不殆,小t首先要做的是知道这个病毒网站特征:包含多少不同的病毒,每种病毒出现了多少次。大家能再帮帮他吗?
思路:
AC自动机模板, 查到一个匹配对匹配的模板加1
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
//#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
#include <string>
#include <assert.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#define MINF 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXN = 2e6+10;
struct AcTree
{
int Next[128];
int fail;
int end;
void Init()
{
memset(Next, 0, sizeof(Next));
end = 0;
fail = 0;
}
}tree[MAXN];
char s[MAXN];
char Sin[1010][100];
int Cnt[1010];
int n, m, cnt;
void Insert(char *s, int id)
{
int len = strlen(s);
int pos = 0;
for (int i = 0;i < len;i++)
{
if (tree[pos].Next[s[i]] == 0)
tree[pos].Next[s[i]] = ++cnt, tree[cnt].Init();
pos = tree[pos].Next[s[i]];
}
tree[pos].end = id;
}
void BuildAC()
{
queue<int> que;
for (int i = 0;i < 128;i++)
{
if (tree[0].Next[i] != 0)
{
tree[tree[0].Next[i]].fail = 0;
que.push(tree[0].Next[i]);
}
}
while (!que.empty())
{
int u = que.front();
que.pop();
for (int i = 0;i < 128;i++)
{
if (tree[u].Next[i] != 0)
{
tree[tree[u].Next[i]].fail = tree[tree[u].fail].Next[i];
que.push(tree[u].Next[i]);
}
else
tree[u].Next[i] = tree[tree[u].fail].Next[i];
}
}
}
void Query(char *s)
{
int len = strlen(s);
int pos = 0;
for (int i = 0;i < len;i++)
{
pos = tree[pos].Next[s[i]];
for (int t = pos;t != 0 && tree[t].end != 0;t = tree[t].fail)
{
Cnt[tree[t].end]++;
}
}
}
int main()
{
while(~scanf("%d", &n))
{
memset(Cnt, 0, sizeof(Cnt));
cnt = 0;
tree[0].Init();
for (int i = 1;i <= n;i++)
{
scanf("%s", Sin[i]);
Insert(Sin[i], i);
}
BuildAC();
scanf("%s", s);
Query(s);
for (int i = 1;i <= n;i++)
{
if (Cnt[i] == 0)
continue;
cout << Sin[i] << ": " << Cnt[i] << endl;
}
}
return 0;
}
标签:HDU,int,tree,AC,Next,pos,3065,fail,include 来源: https://www.cnblogs.com/YDDDD/p/11632157.html