热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

[HDU2896]病毒侵袭[AC自动机]

题意:多模式串匹配,输出模式串的ID思路:典型AC自动机.用向量存储答案ID#include<cstdio>#include<cstring>

题意:

多模式串匹配,输出模式串的ID

思路:

典型AC自动机.

用向量存储答案ID

#include 
#include
#include
#include
#include
#include
using namespace std;
const int MAXL = 130;
/*
inline int GetID(char x)
{
return x;
}*/
class node{
public:
node* chd[MAXL];
node* fail;
int cnt;

node(){
fail = NULL;
memset(chd,0,sizeof(chd));
cnt = 0;
}
};

vector ans;

class AC_Automation{
public:
node* root;
queue q;

AC_Automation(){
root = new node;
while(!q.empty()) q.pop();
}

void insert(string s,int x)
{
node* cur = root;
for(int i=0;i {
int index = s[i];
if(cur->chd[index] == NULL) cur->chd[index] = new node;
cur = cur->chd[index];
}
cur->cnt = x;
}

void BuildAC()
{
node *cur,*tmp;
q.push(root);
while(!q.empty())
{
cur = q.front();
q.pop();
for(int i = 0; i {
if(cur->chd[i])
{//只有root->fail = NULL;
if(cur==root) cur->chd[i]->fail = root;
else
{
tmp = cur->fail;
while(tmp->fail && !tmp->chd[i]) tmp = tmp->fail;
if(tmp->chd[i]) cur->chd[i]->fail = tmp->chd[i];
else cur->chd[i]->fail = root;
}
q.push(cur->chd[i]);
}
}
}
}

void query(string s)
{//用指针时,指向根节点和指向空要分别对待;在fail的构造中已经解决了指向根的跳回
//只需要注意指向空的时候跳回指向根
node *cur = root, *tmp;
for(int i=0;i {
int index = s[i];
if(cur->chd[index]) cur = cur->chd[index];
else
{
while(cur && !cur->chd[index]) cur = cur->fail;
if(!cur) cur = root;
if(cur->chd[index]) cur = cur->chd[index];
}
tmp = cur;
while(tmp->fail && tmp->cnt)
{
ans.push_back(tmp->cnt);
if(ans.size()==3) return;
tmp = tmp->fail;
}
}
}
};
char pat[205],tar[10005];

int main()
{
int n;
while(scanf("%d",&n)==1)
{
AC_Automation AC;
for(int i=1; i<=n; i++)
{
getchar();
gets(pat);
AC.insert(pat,i);
}
AC.BuildAC();
int m,tot = 0;
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
getchar();
gets(tar);
ans.clear();
AC.query(tar);
if(ans.size())
{
sort(ans.begin(),ans.end());
printf("web %d:",i);
for(int j=0;j puts("");
tot++;
}
}
printf("total: %d\n",tot);
}
}



推荐阅读
author-avatar
思念着你2502859117
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有