HDU 2896 病毒侵袭(AC自动机)
此题挺裸的模版的,然后多组的判断,让我WA了很多次,用flag标记一下,就好。。。
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 #define N 60000 6 #define C_NUM 128 7 int trie[N][C_NUM]; 8 int o[N],fail[N],que[N],flag[N]; 9 int t,num; 10 void CL() 11 { 12 memset(trie,-1,sizeof(trie)); 13 memset(o,0,sizeof(o)); 14 memset(fail,0,sizeof(fail)); 15 t = 1; 16 num = 1; 17 } 18 void insert(char *s) 19 { 20 int i,root,len; 21 len = strlen(s); 22 root = 0; 23 for(i = 0;i < len;i ++) 24 { 25 if(trie[root][s[i]] == -1) 26 trie[root][s[i]] = t ++; 27 root = trie[root][s[i]]; 28 } 29 o[root] = num++; 30 } 31 void build_ac() 32 { 33 int head,tail,front,i; 34 head = tail = 0; 35 for (i = 0; i < C_NUM; i++) 36 { 37 if (trie[0][i] != -1) 38 { 39 fail[trie[0][i]] = 0; 40 que[tail++] = trie[0][i]; 41 } 42 else 43 { 44 trie[0][i] = 0; 45 } 46 } 47 while(head != tail) 48 { 49 front = que[head++]; 50 for(i = 0; i < C_NUM; i ++) 51 { 52 if(trie[front][i] != -1) 53 { 54 que[tail++] = trie[front][i]; 55 fail[trie[front][i]] = trie[fail[front]][i]; 56 } 57 else 58 { 59 trie[front][i] = trie[fail[front]][i]; 60 } 61 } 62 } 63 } 64 int judge(char *s,int x) 65 { 66 int temp[4],knum = 0; 67 int i,len,root,key; 68 len = strlen(s); 69 root = 0; 70 for(i = 0;i < len;i ++) 71 { 72 root = trie[root][s[i]]; 73 key = root; 74 while(key != 0&&flag[key] != -1) 75 { 76 if(o[key] > 0&&flag[key] != -1) 77 { 78 temp[knum++] = o[key]; 79 } 80 flag[key] = -1; 81 key = fail[key]; 82 } 83 if(knum == 3) break; 84 } 85 if(knum > 0) 86 { 87 sort(temp,temp+knum); 88 printf("web %d:",x+1); 89 for(i = 0;i < knum;i ++) 90 printf(" %d",temp[i]); 91 printf("\n"); 92 return 1; 93 } 94 else return 0; 95 } 96 int main() 97 { 98 int n,m,i,ans; 99 char ch[10001]; 100 while(~scanf("%d%*c",&n)) 101 { 102 CL(); 103 for(i = 0; i < n; i ++) 104 { 105 gets(ch); 106 insert(ch); 107 } 108 build_ac(); 109 scanf("%d%*c",&m); 110 ans = 0; 111 for(i = 0;i < m;i ++) 112 { 113 gets(ch); 114 memset(flag,0,sizeof(flag)); 115 if(judge(ch,i)) 116 ans ++; 117 } 118 printf("total: %d\n",ans); 119 } 120 return 0; 121 }