poj 3987 Computer Virus on Planet Pandora —— ac自动机复习
作者:互联网
poj 3987 Computer Virus on Planet Pandora ac自动机复习
-
题意如下
给出多个模式串,最后给出一个文本串,求有多少个模式串被文本串包含或者被反序的文本串包含 -
几乎是ac自动机模板,正反跑两次就行了。但是当时板子怎么写忘记了,队里也没带资料,于是没调出来。说明还是基本功不够熟练
代码如下
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int t, n, co = 0, ans = 0;
char pat[1005];
char ss[5100005];
char ss2[5100005];
int que[500005];
bool vis[500005];
struct trie
{
int fl;
int fail;
int nxt[26];
} aca[500005];
void insert(char *s, int l)
{
int o = 0;
int p = 0;
int ls = strlen(s);
while (p < ls)
{
if (!aca[o].nxt[s[p] - 'A'])
{
aca[o].nxt[s[p] - 'A'] = ++co;
}
o = aca[o].nxt[s[p] - 'A'];
++p;
}
++aca[o].fl;
}
void fail_p()
{
int hd = 1, tl = 1;
for (int i = 0; i < 26; ++i)
{
if (aca[0].nxt[i])
{
que[tl++] = aca[0].nxt[i];
aca[aca[0].nxt[i]].fail = 0;
}
}
while (hd != tl)
{
int u = que[hd++];
for (int i = 0; i < 26; ++i)
{
if (aca[u].nxt[i])
{
aca[aca[u].nxt[i]].fail = aca[aca[u].fail].nxt[i];
que[tl++] = aca[u].nxt[i];
}
else
{
aca[u].nxt[i] = aca[aca[u].fail].nxt[i];
}
}
}
}
void query(char *s)
{
int o = 0;
int l = strlen(s);
vis[0] = true;
for (int i = 0; i < l; ++i)
{
int sn = aca[o].nxt[s[i] - 'A'];
while (!vis[sn])
{
ans += aca[sn].fl;
vis[sn] = true;
sn = aca[sn].fail;
}
o = aca[o].nxt[s[i] - 'A'];
}
o = 0;
for (int i = l - 1; i >= 0; --i)
{
int sn = aca[o].nxt[s[i] - 'A'];
while (sn && !vis[sn])
{
ans += aca[sn].fl;
vis[sn] = true;
sn = aca[sn].fail;
}
o = aca[o].nxt[s[i] - 'A'];
}
}
int main()
{
scanf("%d", &t);
while (t--)
{
aca[0].fl = aca[0].fail = 0;
for (int i = 0; i < 26; ++i)
{
aca[0].nxt[i] = 0;
}
co = 0;
ans = 0;
memset(vis, 0, sizeof(vis));
memset(aca, 0, sizeof(aca));
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
{
scanf("%s", pat);
insert(pat, i);
}
fail_p();
scanf("%s", &ss2);
int ll = -1;
int l2 = strlen(ss2);
for (int i = 0; i < l2; ++i)
{
if (ss2[i] != '[')
{
ss[++ll] = ss2[i];
}
else
{
int x = 0;
int j;
for (j = 1; ss2[i + j + 1] != ']'; ++j)
{
x = x * 10 + ss2[i + j] - '0';
}
char c = ss2[i + j];
i += j + 1;
while (x)
{
ss[++ll] = c;
--x;
}
}
}
ss[++ll] = 0;
query(ss);
printf("%d\n", ans);
}
return 0;
}
标签:nxt,aca,int,ac,Planet,++,Virus,sn,fail 来源: https://www.cnblogs.com/int-me-X/p/14095751.html