您的位置:首页 > 其它

LA 4670 (AC自动机 模板题) Dominating Patterns

2015-04-04 20:58 288 查看
AC自动机大名叫Aho-Corasick Automata,不知道的还以为是能自动AC的呢,虽然它确实能帮你AC一些题目。=_=||

AC自动机看了好几天了,作用就是多个模式串在文本串上的匹配。

因为有多个模式串构成了一颗Tire树,不能像以前一样线性递推失配函数f了,于是改成了BFS求失配函数。

白书上那个last数组(后缀链接)的含义就是:在Tire树的某个分支上虽然没有遇到单词节点,但是某个单词可能是已经匹配上的字串的后缀。

举个栗子:

有两个模式串:aaabbb, ab

现在已经匹配了aaab,现在的位置正在Tire树上aaabbb的分支上,明显没有遇到单词节点,但是注意到ab是aaab的后缀,也就是说我们虽然没有匹配到第一个模式串,但是找到第二个模式串ab了。

这就是last数组的作用。

#include <cstdio>
#include <string>
#include <cstring>
#include <queue>
#include <map>
using namespace std;

const int SIGMA_SIZE = 26;
const int MAXNODE = 11000;
const int MAXS = 150 + 10;

map<string, int> ms;

struct AhoCorasickAutomata
{
int ch[MAXNODE][SIGMA_SIZE];
int f[MAXNODE];    //失配函数
int val[MAXNODE];
int last[MAXNODE];
int cnt[MAXS];
int sz;

void init()
{
memset(ch[0], 0, sizeof(ch[0]));
memset(cnt, 0, sizeof(cnt));
ms.clear();
sz = 1;
}

inline int idx(char c) { return c - 'a'; }

//插入字符串s, v > 0
void insert(char* s, int v)
{
int u = 0, n = strlen(s);
for(int i = 0;  i < n; i++)
{
int c = idx(s[i]);
if(!ch[u][c])
{
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;
ch[u][c] = sz++;
}

u = ch[u][c];
}
val[u] = v;
ms[string(s)] = v;
}

//统计每个字串出现的次数
void count(int j)
{
if(j)
{
cnt[val[j]]++;
count(last[j]);
}
}

//在T中查找模板
void find(char* T)
{
int j = 0, n = strlen(T);
for(int i = 0; i < n; i++)
{
int c = idx(T[i]);
while(j && !ch[j][c]) j = f[j];
j = ch[j][c];
if(val[j]) count(j);
else if(last[j]) count(last[j]);
}
}

//计算失配函数
void getFail()
{
queue<int> q;
f[0] = 0;
for(int i = 0; i < SIGMA_SIZE; i++)
{
int u = ch[0][i];
if(u) { last[u] = 0; f[u] = 0; q.push(u); }
}
while(!q.empty())
{
int r = q.front(); q.pop();
for(int c = 0; c < SIGMA_SIZE; c++)
{
int u = ch[r][c];
if(!u) continue;
q.push(u);
int v = f[r];
while(v && !ch[v][c]) v = f[v];
f[u] = ch[v][c];
last[u] = val[f[u]] ? f[u] : last[f[u]];
}
}
}
}ac;

const int maxn = 1000000 + 10;
char T[maxn], P[160][80];

int main()
{
//freopen("in.txt", "r", stdin);

int n;
while(scanf("%d", &n) == 1 && n)
{
ac.init();
for(int i = 1; i <= n; i++) { scanf("%s", P[i]); ac.insert(P[i], i); }
scanf("%s", T);
ac.getFail();
ac.find(T);
int M = -1;
for(int i = 1; i <= n; i++) if(ac.cnt[i] > M) M = ac.cnt[i];
printf("%d\n", M);
for(int i = 1; i <= n; i++)
if(ac.cnt[ms[string(P[i])]] == M)
printf("%s\n", P[i]);
}

return 0;
}


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