Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7454 Accepted Submission(s): 1961
3 aaa bbb ccc 2 aaabbbccc bbaacc
web 1: 1 2 3 total: 1
#include<iostream> #include<cstring> #include<cstdio> #include<queue> #include<algorithm> using namespace std; const int ch_size=127; int n,m; bool vis[505]; class node { public:int val; node*next[127]; node*fail; node(){memset(next,NULL,sizeof(next));fail=NULL;val=0;} }*root; void insert(node*root,char*s,int id) { node*tmp=root;int z; for(int i=0;s[i];++i) { z=s[i]; if(tmp->next[z]==NULL) tmp->next[z]=new node(); tmp=tmp->next[z]; } tmp->val=id; } void get_fail(node*root) { node*tmp,*ret,*p; queue<node*>Q; Q.push(root); while(!Q.empty()) { tmp=Q.front();Q.pop(); for(int i=0;i<ch_size;++i) { if(tmp->next[i]==NULL)continue; p=tmp->fail; while(p!=NULL&&p->next[i]==NULL)p=p->fail; if(p==NULL)tmp->next[i]->fail=root; else tmp->next[i]->fail=p->next[i]; Q.push(tmp->next[i]); } } } bool query(node*root,char*s,int id) { bool flag=0; memset(vis,0,sizeof(vis)); int z;node*tmp=root,*ret; for(int i=0;s[i];++i) { z=s[i]; while(tmp!=root&&tmp->next[z]==NULL)tmp=tmp->fail; tmp=tmp->next[z]; if(tmp==NULL)tmp=root; ret=tmp; while(ret!=root&&ret!=NULL) { if(ret->val>0){vis[ret->val]=1;flag=1;}ret=ret->fail; } } if(flag) {printf("web %d:",id); for(int i=1;i<=n;++i) if(vis[i]) {printf(" %d",i);flag=1;} printf("\n"); } return flag; } void mefree(node*tmp) { for(int i=0;i<ch_size;++i) { if(tmp->next[i]!=NULL) mefree(tmp->next[i]); } delete tmp; } char s[11000]; int main() { while(~scanf("%d",&n)) { root=new node(); for(int i=0;i<n;++i) { scanf("%s",s); insert(root,s,i+1); } scanf("%d",&m); int total=0; get_fail(root); for(int i=0;i<m;++i) { scanf("%s",s); if(query(root,s,i+1)) ++total; } printf("total: %d\n",total); mefree(root); } return 0; }