AC自动机-HDU2896-模板题

时间:2023-03-10 00:47:49
AC自动机-HDU2896-模板题

http://acm.hdu.edu.cn/showproblem.php?pid=2896

另一道AC自动机的模板题,不过这题需要记录一下具体的匹配情况。

/*--------------------------------------------------------------------------------------*/
// Helica's header
// Second Editions
// 2015.11.7
//
#include <algorithm>
#include <iostream>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map> //debug function for a N*M array
#define debug_map(N,M,G) printf("\n");for(int i=0;i<(N);i++)\
{for(int j=;j<(M);j++){\
printf("%d",G[i][j]);}printf("\n");}
//debug function for int,float,double,etc.
#define debug_var(X) cout<<#X"="<<X<<endl;
/*--------------------------------------------------------------------------------------*/
using namespace std; int N,M,T;
int tol; struct Trie
{
int next[][],fail[],end[];
int num[];
int root,L;
int cnt;
int newnode()
{
for(int i=;i<;i++)
next[L][i] = -;
end[L++] = ;
return L-;
}
void init()
{
L = ;
root = newnode();
memset(num,,sizeof num);
cnt = ;
}
void insert(char *s)
{
int len = strlen(s);
int now = root;
for(int i=;i<len;i++)
{
if(next[now][s[i]-'!'] == -)
next[now][s[i]-'!'] = newnode();
now = next[now][s[i]-'!'];
}
end[now]++;
num[now] = cnt++;
}
void build()
{
queue <int> Q;
fail[root] = root;
for(int i=;i<;i++)
{
if(next[root][i] == -)
next[root][i] = root;
else
{
fail[next[root][i]] = root;
Q.push(next[root][i]);
}
}
while(! Q.empty())
{
int now = Q.front();
Q.pop();
for(int i=;i<;i++)
{
if(next[now][i] == -)
next[now][i] = next[fail[now]][i];
else
{
fail[next[now][i]] = next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
}
void query(char *s,int no)
{
int len = strlen(s);
int now = root;
int ans = ;
set <int > web; for(int i=;i<len;i++)
{
now = next[now][s[i]-'!'];
int temp = now;
while(temp != root)
{
ans += end[temp];
if(end[temp]) web.insert(num[temp]);
temp = fail[temp];
}
}
if(!web.empty())
{
printf("web %d:",no);
for(set <int>::iterator it=web.begin();it != web.end();it++)
printf(" %d",*it);
printf("\n");
tol++;
}
}
}ac; char buf[]; int main()
{
while(~scanf("%d",&N))
{
ac.init();
tol = ;
for(int i=;i<N;i++)
{
scanf("%s",buf);
ac.insert(buf);
}
ac.build();
scanf("%d",&M);
for(int i=;i<=M;i++)
{
scanf("%s",buf);
ac.query(buf,i);
}
printf("total: %d\n",tol);
}
}