您的位置:首页 > 其它

HDU 2222 Keywords Search

2013-08-19 11:03 351 查看
比较裸的AC自动机。

借鉴:http://www.cppblog.com/mythit/archive/2009/04/21/80633.html

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef __int64 int64;
typedef long long ll;
#define M 500005
#define N 1000005
#define max_inf 0x7f7f7f7f
#define min_inf 0x80808080
const int  mod = 1e6;

struct node
{
node *fail;
node *next[26];
int cout;
node()
{
fail = NULL;
memset(next , NULL , sizeof next);
cout = 0;
}
}*q[M];
char str
;
int n;

void Insert(char *str , node *rt)
{
int i = 0;
node *p = rt;
while (str[i])
{
int inx = str[i]-'a';
if (!p->next[inx])p->next[inx] = new node;
p = p->next[inx];
i++;
}
p->cout++;
}

void Build(node *rt)
{
rt->fail = NULL;
int head , tail;
head = tail = 0;
q[tail++] = rt;
while (head < tail)
{
int i;
node *p = q[head++];
for (i = 0 ; i < 26 ; i++)
{
if (!p->next[i])continue;
if (p == rt)p->next[i]->fail = rt;
else
{
node *temp = p->fail;
while (temp)
{
if (temp->next[i])
{
p->next[i]->fail = temp->next[i];
break;
}
temp = temp->fail;
}
if (!temp)p->next[i]->fail = rt;
}
q[tail++] = p->next[i];
}
}
}

void Solve(node *rt)
{
int i = 0 , ans = 0;
node *p = rt;
while (str[i])
{
int inx = str[i]-'a';
while (!p->next[inx] && p != rt)p = p->fail;
p = p->next[inx];
if (!p)p = rt;
node *temp = p;
while (temp != rt)
{
ans += temp->cout;
temp->cout = 0;
temp = temp->fail;
}
i++;
}
printf("%d\n",ans);
}

int main()
{
int t;
scanf("%d",&t);
while (t--)
{
char keyword[55];
node *rt = new node;
scanf("%d",&n);
while (n--)
{
scanf("%s",keyword);
Insert(keyword,rt);
}
Build(rt);
scanf("%s",str);
Solve(rt);
}
}


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