3 aaa bbb ccc 2 aaabbbccc bbaacc
web 1: 1 2 3 total: 1
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
char str1[222],str2[11111];
int total=0;
struct Node{
Node *fail,*next[128];
int id;
Node(){
fail=NULL;
for(int i=0;i<128;i++)
next[i]=NULL;
id=-1;
}
}*q[511111],*root;
void tree_insert(char *str,int num){
Node *p=root;
int l=strlen(str);
for(int i=0;i<l;i++){
int index=str[i]-31;
if(p->next[index]==NULL){
p->next[index]=new Node();
}
p=p->next[index];
}
p->id=num;
}
void build_ac_automachine(){
int fr,ed;
fr=ed=0;
Node *p,*temp;
q[ed++]=root;
root->fail=NULL;
while(fr<ed){
temp=q[fr++];
for(int i=0;i<128;i++){
if(temp->next[i]!=NULL){
if(temp==root)
temp->next[i]->fail=root;
else {
p=temp->fail;
while(p){
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[ed++]=temp->next[i];
}
}
}
}
void solve(char *str,int num){
int l=strlen(str);
int ans[555];
int scnt=0;
Node *p,*temp;
p=root;
for(int i=0;i<l;i++){
int index=str[i]-31;
while(p->next[index]==NULL&&p!=root)p=p->fail;
p=p->next[index];
if(p==NULL)
p=root;
temp=p;
while(temp!=root){
if(temp->id>0)
ans[++scnt]=temp->id;
temp=temp->fail;
}
}
if(scnt==0)
return ;
printf("web %d: ",num);
sort(ans+1,ans+1+scnt);
total++;
for(int i=1;i<scnt;i++)
printf("%d ",ans[i]);
printf("%d\n",ans[scnt]);
}
int main(){
int n,m;
total=0;
scanf("%d",&n);
root=new Node();
for(int i=1;i<=n;i++){
scanf("%s",str1);
tree_insert(str1,i);
}
build_ac_automachine();
scanf("%d",&m);
for(int i=1;i<=m;i++){
scanf("%s",str2);
solve(str2,i);
}
printf("total: %d\n",total);
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/qq_16843991/article/details/46893885