http://acm.hdu.edu.cn/showproblem.php?pid=2896
裸!
只有一点要注意,就是这里面的字符串不只是字母,KIND 应该定义成128,我开始想都没想直接256,mle
还有就是读的时候用gets,因为a aaa 这种也算中间有空格的,其它的就是题目说了病毒数不会超过三,所以最多输出三个
我遇到的恶心的地方就这几个,注意到了应该就能ac了
/* * File: main.cpp * Author: Mi * * Created on 2011年4月1日, 下午3:14 */ #include <cstdlib> #include <stdio.h> #include <string.h> #include <algorithm> #define N 500*200+5 #define MAX 10005 #define KIND 128 using namespace std; /* * */ char msg[MAX]; int vis[505]; struct node { node *fail; node *next[KIND]; int num; node() { fail=NULL; memset(next,NULL,sizeof(next)); num=0; } }*que[N],*root; void Insert(node *root,char *s,int num) { node *p=root; for(int i=0;s[i];i++) { int index=s[i]; if(p->next[index]==NULL) p->next[index]=new node; p=p->next[index]; } p->num=num; } void Build_AC_Automation(node *root) { int head=0,tail=0; root->fail=NULL; que[head++]=root; while(head!=tail) { node *cur=que[tail++]; for(int i=0;i<KIND;i++) if(cur->next[i]!=NULL) { if(cur==root) cur->next[i]->fail=root; else { node *ptr=cur->fail; while(ptr!=NULL) { if(ptr->next[i]!=NULL) { cur->next[i]->fail=ptr->next[i]; break; } ptr=ptr->fail; } if(ptr==NULL) cur->next[i]->fail=root; } que[head++]=cur->next[i]; } } } int AC_search(node *root,char *msg) { int ans=0; node *ptr=root; for(int i=0;msg[i];i++) { int index=msg[i]; while(ptr->next[index]==NULL&&ptr!=root) ptr=ptr->fail; ptr=ptr->next[index]; if(ptr==NULL) ptr=root; node *temp=ptr; while(temp!=NULL&&temp->num) { // ans+=temp->cnt; // temp->cnt=-1; ans=1; vis[temp->num]=1; temp=temp->fail; } } return ans; } int main(int argc, char** argv) { int n,flag[1005],i,total=0; scanf("%d/n",&n); root=new node; memset(flag,0,sizeof(flag)); for(i=0;i<n;i++) { char s[205]; gets(s); Insert(root,s,i+1); } Build_AC_Automation(root); scanf("%d/n",&n); for(i=0;i<n;i++) { int temp; memset(vis,0,sizeof(vis)); gets(msg); temp=AC_search(root,msg); if(temp) { total++; printf("web %d:",i+1); for(int j=1,cnt=0;j<505;j++) if(vis[j]) { printf(" %d",j); cnt++; if(cnt==3) break; } printf("/n"); } } printf("total: %d/n",total); return 0; }