您的位置:首页 > 其它

HDOJ 2222

2014-04-30 18:36 337 查看

思路: AC自动机

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct Node_Tree
{
int cnt;
struct Node_Tree *child[26];
struct Node_Tree *fail;
}Node;
Node *root;
char keywd[51];
char decpt[1000001];
Node *q[500001];
int tail = 0, head = 0;
void insert()
{
if(keywd == NULL)
return ;
int i;
char *p = keywd;
Node *t = root;
while(*p != '\0')
{
if(t->child[*p - 'a'] == NULL)
{
Node *temp = (Node *)malloc(sizeof(Node));
memset(temp, 0, sizeof(Node));
for(i = 0; i < 26; i ++)
{
temp->child[i] = NULL;
}
temp->cnt = 0;
temp->fail = NULL;
t->child[*p - 'a'] = temp;
}
t = t->child[*p - 'a'];
p ++;
}
t->cnt ++;
}

void getfail()
{
int i;
q[tail++] = root;
while(tail != head)             //BFS;
{
Node *p = q[head++];
Node *temp = NULL;
for(i = 0; i < 26; i ++)
{
if(p->child[i] != NULL)
{
if(p == root)
{
p->child[i]->fail = root;
}
else
{
temp = p->fail;
while(temp != NULL)
{
if(temp->child[i] != NULL)
{
p->child[i]->fail = temp->child[i];
break ;
}
temp = temp->fail;
}
if(temp == NULL)
p->child[i]->fail = root;
}
q[tail++] = p->child[i];
}
}
}
}

int search()
{
int i, ret = 0;
char *p = decpt;
Node *t = root;
while(*p != '\0')
{
while(t->child[*p - 'a'] == NULL && t != root)
t = t->fail;
t = t->child[*p - 'a'];
if(t == NULL)
t = root;
Node *temp = t;
while(temp != root && temp->cnt != -1)
{
ret += temp->cnt;
temp->cnt = -1;
temp = temp->fail;
}
p ++;
}
return ret;
}

int main(int argc, char const *argv[])
{
int c, i, t;
scanf("%d", &c);
Node TREEROOT;
root = &TREEROOT;
while(c --)
{
for(i = 0; i < 30; i ++)
{
root->child[i] = NULL;
root->cnt = 0;
root->fail = NULL;
}
tail = head = 0;
memset(decpt, 0, sizeof(decpt));
memset(keywd, 0, sizeof(keywd));
scanf("%d", &t);
while(t --)
{
scanf("%s", keywd);
insert();
memset(keywd, 0, sizeof(keywd));
}
getfail();
scanf("%s", decpt);
printf("%d\n", search());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: