uva10815--没过

来源:互联网 发布:app源码制作 编辑:程序博客网 时间:2024/06/09 16:46

//#define LOCAL#include <algorithm>#include <stdio.h>#include <string.h>#include <ctype.h>#define MAXN 50000 + 10#define MAX 50000 + 10 char word[MAX];const int sonsum = 26;char base = 'a';int count;struct Trie {int num;//to remeber how many word can reach here, that is to say,perfix bool terminal;// If terminal == true, the current point has no following pointstruct Trie * son[sonsum];// the following point};Trie *NewTrie();void FindAll(Trie *, char *, int);void Insert(Trie *pnt, char *s, int len);void Delete(Trie *pnt);Trie* Find(Trie *pnt, char *s, int len);char* my_strlwr(char *str);int main()  {  #ifdef LOCAL      freopen("input.txt", "r", stdin);      //freopen("output.txt", "w", stdout);  #endifint i, j;// 数据的初始化 Trie* root = new Trie;root->num = 0;root->terminal = false;for(i = 0; i < sonsum; i++)root->son[i] = NULL;while(scanf("\n%s", word) != EOF){// 将单词插入字典树 Insert(root, word, strlen(word));}  // 深搜遍历字典树,输出结果  memset(word, 0, sizeof(word));FindAll(root, word, 0);return 0;}Trie *NewTrie()// Create a new node{Trie *temp = new Trie;temp->num = 1;temp->terminal = false;for(int i = 0; i < sonsum; i++)temp->son[i] = NULL;return temp;}void Insert(Trie *pnt, char *s, int len)// insert a new word to Trie tree{Trie *temp = pnt;s = my_strlwr(s);for(int i = 0; i < len; i++){if(isalpha(s[i])){if(temp->son[s[i] - base] == NULL)temp->son[s[i] - base] = NewTrie();else temp->son[s[i] - base]->num++;temp = temp->son[s[i] - base];}}temp->terminal = true;}void Delete(Trie *pnt)// delete the whole tree{if(pnt != NULL){for(int i = 0; i < sonsum; i++)if(pnt->son[i] != NULL)Delete(pnt->son[i]);delete pnt;pnt = NULL;}}Trie* Find(Trie *pnt, char *s, int len)// trie to find the current word{Trie *temp = pnt;for(int i = 0; i < len; i++){if(temp->son[s[i] - base] != NULL)temp = temp->son[s[i] - base];elsereturn NULL;return temp;} }// 树的遍历 void FindAll(Trie *trie, char* word, int len){int i;if(trie->terminal && len != 0){word[len] = '\0';printf("%s\n", word);}for(i = 0; i < sonsum; i++){if(trie->son[i] != NULL){word[len++] = i + 'a';FindAll(trie->son[i], word, len); len--;}}}char * my_strlwr(char *str){   char *p = str;   while (*p != '/0')   {      if(*p >= 'A' && *p <= 'Z')        *p = (*p) + 0x20;      p++;      if(*p == '\0')      return str;    }  return str;}

这个题目比较简单,但是就是想用字典树做,结果。。两天了,悲剧啊。。。


原创粉丝点击