3aaabbbccc2aaabbbcccbbaacc
web 1: 1 2 3total: 1
源代码:(171MS)
#include<iostream> #include<algorithm> #include<string.h> using namespace std; const int KIND=100; const int MAX=10005; int n,m,ans,visit[100000];//visit[]标志已记录的结点 int allocp=0; struct TrieNode { int *vis,num; TrieNode *fail; TrieNode *next[KIND]; TrieNode() { vis=&visit[allocp++];//指针指向visit数组 num=0; fail=NULL; memset(next,0,sizeof(next)); } }; TrieNode *q[500005];//队列 void InsertTrieNode(TrieNode *pRoot,char s[],int number) { TrieNode *p=pRoot; int i=0; while(s[i]) { int k=s[i]-32; if(p->next[k]==NULL) p->next[k]=new TrieNode(); i++; p=p->next[k]; } p->num=number; } void Build_AC_automation(TrieNode *pRoot) { int head=0,tail=0,i; TrieNode *p; pRoot->fail=NULL; q[tail++]=pRoot; while(head!=tail) { p=q[head++]; for(i=0;i<KIND;i++) if(p->next[i]!=NULL) { if(p==pRoot) p->next[i]->fail=pRoot; TrieNode *tmp=p->fail; while(tmp!=NULL && tmp->next[i]==NULL) tmp=tmp->fail; if(tmp==NULL) p->next[i]->fail=pRoot; else p->next[i]->fail=tmp->next[i]; q[tail++]=p->next[i]; } } } void Search(TrieNode *pRoot,char s[],int webNum) { int i,res=0,cnt[3]; TrieNode *p,*tmp; p=pRoot; i=0; while(s[i]) { int k=s[i++]-32; while(p->next[k]==NULL && p!=pRoot) p=p->fail; p=p->next[k]; if(p==NULL) p=pRoot; tmp=p; while(tmp!=pRoot&& *(tmp->vis)!=-1)// { if(tmp->num>0) cnt[res++]=tmp->num; *(tmp->vis)=-1; //搜索过 tmp=tmp->fail; } } if(res) { ans++; sort(cnt,cnt+res); printf("web %d:",webNum); for(i=0;i<res;i++) cout<<" "<<cnt[i]; cout<<endl; } } void Reset()//为下一个网站重置vis { for(int i=0;i<allocp;i++) visit[i]=2; } int main() { int i,j; TrieNode *pRoot=new TrieNode(); char word[205],s[MAX]; while(scanf("%d",&n)!=EOF) { memset(pRoot->next,NULL,sizeof(pRoot->next)); allocp=1; getchar(); for(i=1;i<=n;i++) { gets(word); InsertTrieNode(pRoot,word,i); } Build_AC_automation(pRoot); scanf("%d",&m); ans=0; getchar(); for(i=1;i<=m;i++) { gets(s); Reset(); Search(pRoot,s,i); } cout<<"total: "<<ans<<endl; } system("pause"); return 0; }