还是一道裸的AC自动机的题目,但是字符集扩大了。字符都是ASCII码可见字符。不知道什么是字符都是ASCII码可见字符,所以RE了很多次,囧!
下面是代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int maxn = 10005;
const int maxc = 128;
int ch[maxn*6][maxc];
int val[maxn*6];
int f[maxn*6];
int vis[maxn*6];
int cnt;
int ID;
char s[250],str[maxn];
int init()
{
cnt = 1;
ID = 1;
memset(ch[0],0,sizeof(ch[0]));
}
void ac_insert_trie(char *s)
{
int u = 0;
while(*s)
{
int id = *s - ' ';
if(ch[u][id] == 0)
{
memset(ch[cnt],0,sizeof(ch[cnt]));
val[cnt] = 0;
ch[u][id] = cnt++;
}
u = ch[u][id];
s++;
}
val[u] = ID++;
}
void ac_get_fail()
{
queue<int> q;
for(int c = 0; c < maxc; c++)
{
int u = ch[0][c];
if(u)
{
f[u] = 0;
q.push(u);
}
}
while(!q.empty())
{
int r = q.front(); q.pop();
for(int c = 0; c < maxc; c++)
{
int u = ch[r][c];
if(u)
{
q.push(u);
int v = f[v];
while(v && ch[v][c]) v = f[v];
f[u] = ch[v][c];
}
}
}
}
bool ac_find(int len)
{
int j = 0;
bool ok = false;
for(int i = 0; i < len; i++)
{
int u = str[i] - ' ';
while(j && !ch[j][u]) j = f[j];
j = ch[j][u];
int t = j;
while(t && !vis[t] && val[t])
{
vis[t] = 1;
t = f[t];
ok = true;
}
}
if(ok) return true;
return false;
}
int main()
{
int N,M;
scanf("%d",&N);
init();
for(int i = 0; i < N; i++)
{
scanf("%s",s);
ac_insert_trie(s);
}
ac_get_fail();
scanf("%d",&M);
int ans = 0;
for(int i = 1; i <= M; i++)
{
scanf("%s",str);
memset(vis,0,sizeof(vis));
if(ac_find(strlen(str)))
{
printf("web %d:",i);
ans++;
for(int j = 0; j < cnt; j++)
{
int flag = 0;
if(vis[j]) printf(" %d",val[j]),flag++;
if(flag == 3) break;
}
printf("\n");
}
}
printf("total: %d\n",ans);
}