题目意思 就是说给你N个病毒,M 个模式串,分别找出这M个模式串里面有哪些病毒,把标号给输出来; 方法 首先 因为要用到多次,所以用一个 标记 看这是第几次进去,接下来就是模板题了; 1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 7 struct date 8 { 9 int num,tab; 10 date *next[130],*fail; 11 date( ) 12 { 13 memset( next,NULL,sizeof(next)); 14 fail = NULL; 15 num = tab = 0; 16 } 17 }*que[112345],*root; 18 19 int tail,head,ptr,k,res[555]; 20 char str[11234]; 21 22 void inint( ) 23 { 24 tail = head = ptr = 0; 25 root = new date; 26 } 27 28 void insert( char *word,int tab ) 29 { 30 date *temp = root; 31 while( *word ) 32 { 33 int num = *word; 34 if( temp->next[num] == NULL ) 35 temp->next[num] = new date; 36 temp = temp->next[num]; 37 word++; 38 } 39 temp->num = 0; 40 temp->tab = tab; 41 } 42 43 void build_AC( ) 44 { 45 que[tail++] = root; 46 while( tail > head ) 47 { 48 date *temp = que[head++]; 49 for( int i = 0; i < 130; i++ ) 50 if( temp->next[i] != NULL ) 51 { 52 if( temp == root ) temp->next[i]->fail = root; 53 else temp->next[i]->fail = temp->fail->next[i]; 54 que[tail++] = temp->next[i]; 55 } 56 else 57 { 58 if( temp == root ) temp->next[i] = root; 59 else temp->next[i] = temp->fail->next[i]; 60 } 61 } 62 } 63 64 int query( char *word,int i ) 65 { 66 date *patten,*temp = root; 67 while( *word ) 68 { 69 int num = *word; 70 temp = temp->next[num]; 71 patten = temp; 72 while( patten != root ) 73 { 74 if( patten->num != i ) 75 { 76 patten->num = i; 77 if( patten->tab ) 78 res[k++] = patten->tab; 79 } 80 else break; 81 patten = patten->fail; 82 } 83 word++; 84 } 85 return 0; 86 } 87 88 int main( ) 89 { 90 int N,M,i,j,ans; 91 while( scanf("%d",&N) != EOF ) 92 { 93 inint(); 94 for( i = 1; i <= N; i++ ) 95 { 96 scanf("%s",&str); 97 insert(str,i); 98 } 99 build_AC( );100 scanf("%d",&M); 101 ans = 0;102 for( i = 1; i <= M; i++ )103 {104 scanf("%s",&str);105 k = 0; query( str,i );106 if( k ) ans++,printf("web %d:",i);107 if( k ) sort( res,res+k );108 for( j = 0; j < k; j++ )109 printf(" %d",res[j]);110 if( k ) printf("\n");111 }112 printf("total: %d\n",ans);113 }114 return 0;115 }