AC automata, static arrays, dynamically allocated tle.
1 /*1277*/2#include <iostream>3#include <cstdio>4#include <cstring>5#include <cstdlib>6#include <queue>7 using namespacestd;8 9 #defineMAXL 60005Ten #defineTrien 10 One AtypedefstructTrie { - intN; -Trie *fail; theTrie *Next[trien]; - } Trie; - -Trie tries[1000024]; + intNtrie; - CharS[MAXL]; + Charstr[ $]; A intans[10005], N; at BOOLFlag; -Trie *Root; - -Trie *NewNode () { -memset (Tries[ntrie].next,0,sizeof(Tries[ntrie].next)); -TRIES[NTRIE].N =0; inTries[ntrie].fail =NULL; - return&tries[ntrie++]; to } + - voidCreateCharStr[],intv) { the inti =0, id; *Trie *p = root, *Q; $ Panax Notoginseng while(Str[i]) { -id = str[i]-'0'; the++i; + if(P->next[id] = =NULL) { AQ =NewNode (); theP->next[id] =Q; + } -p = p->Next[id]; $ } $P->n =v; - } - the voidBuild_fail () { - inti;WuyiTrie *p, *Q; theQueue<trie *>Q; - Wu for(i=0; i<trien; ++i) { - if(root->Next[i]) { AboutRoot->next[i]->fail =Root; $Q.push (root->next[i]); - } - } - A while(!Q.empty ()) { +p =Q.front (); the Q.pop (); - for(i=0; i<trien; ++i) { $ if(p->Next[i]) { theQ = p->fail; the while(q) { the if(q->Next[i]) { theP->next[i]->fail = q->Next[i]; - Break; in } theQ = q->fail; the } About if(q = =NULL) theP->next[i]->fail =Root; theQ.push (p->next[i]); the } + } - } the }Bayi the voidSearchChars[]) { the inti =0, id; -Trie *p = root, *Q; - the while(S[i]) { theid = s[i]-'0'; the++i; the while(P->next[id]==null && p!=root) -p = p->fail; thep = p->Next[id]; the if(p = =NULL) thep =Root;94Q =p; the while(Q! =root) { the if(q->N) { theFlag =true;98ans[n++] = q->N; AboutQ->n =0; - }101Q = q->fail;102 }103 }104 } the 106 voidDel (Trie *t) {107 if(T = =NULL)108 return ;109 for(intI=0; i<trien; ++i) theDel (t->next[i]);111 Free (t); the }113 the voidinit () { then =0; theFlag =false;117Ntrie =0;118Root =NewNode ();119 } - 121 intMain () {122 intT, M;123 intI, J, K;124 the #ifndef Online_judge126Freopen ("data.in","R", stdin);127 //freopen ("Data.out", "w", stdout); - #endif129 the while(SCANF ("%d%d", &t, &m)! =EOF) {131 for(i=0; i<t; ++i) { thescanf"%s%*c", str);133 strcat (S, str);134 }135 GetChar ();136 init ();137 for(i=1; i<=m; ++i) {138scanf"%*s%*s%*s%s", str);139 Create (str, i); $ }141 Build_fail ();142 search (s);143 if(flag) {144printf"Found Key:");145 for(i=0; i<n; ++i)146printf"[Key No.%d]", Ans[i]);147printf"\ n");148}Else {149printf"No key can be found!\n"); Max }151 } the 153 return 0;154}
"Hdoj" 1277 full Text Search