Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 16970 Accepted Submission(s):
6098
You are to find all the hat’s words in a dictionary.
Only one case.
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 using namespace std; 6 7 typedef struct node 8 { 9 int f; 10 struct node *nxt[26]; 11 }Trie; 12 13 void insert(Trie *root, char *str)//字典树的更新操作 14 { 15 if (root == NULL || *str=='\0') return; 16 Trie *p = root; 17 while (*str != '\0') 18 { 19 if (p->nxt[*str - 'a'] == NULL)//当前结点为空,就在其下开26个空间 20 { 21 Trie *q= (Trie *)malloc(sizeof(Trie));//开辟内存空间 22 q->f = 0; 23 for (int i = 0; i < 26; i++) 24 { 25 q->nxt[i] = NULL; 26 } 27 p->nxt[*str - 'a'] = q; 28 p = p->nxt[*str - 'a'];//使p指向新开辟的内存空间 29 } 30 else p = p->nxt[*str - 'a']; 31 str += 1; 32 } 33 p->f = 1;//在单词末尾标记 34 } 35 36 int find(Trie *root, char *str) 37 { 38 Trie *p = root; 39 while (*str != '\0') 40 { 41 if (p->nxt[*str - 'a'] == NULL) return 0; 42 p = p->nxt[*str - 'a']; 43 str += 1; 44 } 45 return p->f; 46 } 47 48 char cstr[50050][100]; 49 int main() 50 { 51 char c1[100], c2[100]; 52 Trie *root = (Trie*)malloc(sizeof(Trie));//开辟根节点内存空间 53 root->f = 0; 54 int i; 55 for (i = 0; i < 26; i++) 56 { 57 root->nxt[i] = NULL; 58 } 59 int cnt = 0; 60 while (scanf("%s", cstr[cnt]) != EOF) 61 { 62 insert(root, cstr[cnt]); 63 cnt++; 64 } 65 memset(c1, '\0', sizeof(c1));//初始化c1,c2 66 memset(c2, '\0', sizeof(c2)); 67 int j; 68 for (i = 0; i < cnt; i++) 69 { 70 for (j = 1; j < strlen(cstr[i]); j++) 71 { 72 strcpy(c1, cstr[i]); 73 c1[j] = '\0';//将cstr中0~j字符串复制的c1 74 strcpy(c2, cstr[i] + j);//将cstr中j~最后字符串复制到c2 75 if (find(root, c1) && find(root, c2)) 76 { 77 printf("%s\n", cstr[i]); 78 break; 79 } 80 } 81 } 82 return 0; 83 }