Title Link: http://acm.acmcoder.com/showproblem.php?pid=1671
Test instructions: Ask if there is a string that is the prefix of another string.
Solution: Build a dictionary tree, insert the end of the string to set the flag bit, if later access to, then there is a string is another string prefix. Pay attention to freeing up memory, otherwise super memory, (too weak, release memory to tune for a long time ...)
Code:
#include <stdio.h>#include <iostream>#include <string.h>#include <algorithm>#include <math.h>#include <ctype.h>#include <time.h>#include <queue>#include <iterator>using namespace STD;typedef structtrie{intVis Trie *next[Ten];} Trie; Trie *root;intOkvoidCreatetrie (CharStr[]) {if(OK)return;intLen =strlen(str); Trie *p = root, *q;intId for(inti =0; i<len; ++I) {id = str[i]-' 0 ';if(P->next[id] = = NULL) {q =NewTrie; for(intj =0; j<Ten; ++J) Q->next[j] = NULL; P->next[id] = q; P->next[id]->vis =1;if(i = = len-1) P->next[id]->vis =-1; p = p->next[id]; }Else{if(P->next[id]->vis = =-1|| Str[i +1] ==' + ') {OK =1;return; }if(i = = Len-1) P->next[id]->vis =-1; p = p->next[id]; } }}voidFree_memory (Trie *p) { for(inti =0; I <Ten; i++) {if(P->next[i]! = NULL) free_memory (P->next[i]); } Free(p);}Charstr[1001000];intT, N;intMain () {scanf("%d", &t); while(t--) {OK =0; Root =NewTrie; for(inti =0; I <Ten; i++) {Root->next[i] = NULL; Root->vis =0; }scanf("%d", &n); for(inti =1; I <= N; i++) {scanf('%s ', str); Createtrie (str); }if(!ok)puts("YES");Else puts("NO"); Free_memory (root); }return 0;}
HDU 1671&&poj 3630 Phone List "Dictionary tree"