题意:给了病毒编号,又给了网站,问哪些网站中了病毒,并将中的病毒编号输出,最后输出共有多少网站中病毒
思路:AC自动机模版题,将结构体里的num记为病毒编号就行了,我的代码如果将N设为128就会超内存,但是可见的ASCII只有32到127,不用计算空格,94就可以了
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=5000010;
const int N=94;
struct node{
node *fail;
node *next[N];
int num;
node(){
fail=NULL;
num=0;
memset(next,NULL,sizeof(next));
}
}*q[maxn];
char str2[10003];
bool vis[503];
int head,tail;
void insert_Trie(char *str,node *root,int cn){
node *p=root;
int i=0;
while(str[i]){
int id=str[i]-' ';
if(p->next[id]==NULL) p->next[id]=new node();
p=p->next[id];i++;
}
p->num=cn;
}
void build_ac(node *root){
root->fail=NULL;
q[head++]=root;
while(head!=tail){
node *temp=q[tail++];
node *p=NULL;
for(int i=0;i<N;i++){
if(temp->next[i]!=NULL){
if(temp==root) temp->next[i]->fail=root;
else{
p=temp->fail;
while(p!=NULL){
if(p->next[i]!=NULL){
temp->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL) temp->next[i]->fail=root;
}
q[head++]=temp->next[i];
}
}
}
}
int query(node *root){
int i=0,ans=0;
node *p=root;
while(str2[i]){
int id=str2[i]-' ';
while(p->next[id]==NULL&&p!=root) p=p->fail;
p=p->next[id];
p=(p==NULL)?root:p;
node *temp=p;
while(temp!=root){
vis[temp->num]=1;
if(temp->num!=0) ans++;
temp=temp->fail;
}
i++;
}
return ans;
}
int main(){
int n,m;
while(scanf("%d",&n)!=-1){
node *root=new node();
head=tail=0;
for(int i=0;i<n;i++){
scanf("%s",str2);
insert_Trie(str2,root,i+1);
}
build_ac(root);
scanf("%d",&m);
int sum=0;
for(int i=1;i<=m;i++){
scanf("%s",str2);
memset(vis,0,sizeof(vis));
int tt=query(root);
if(tt){
sum++;
printf("web %d:",i);
for(int j=1;j<=n;j++){
if(vis[j]) printf(" %d",j);
}
printf("\n");
}
}
printf("total: %d\n",sum);
}
return 0;
}