pku2001 Shortest Prefixes (trie)

trie, 查找区别其他字符串的最短前缀。

 

#include <stdio.h> #include <string.h> char str[1010][25]; int n; const int kind=26; //字母种类 struct Treenode //树的结点结构 { int count; //这个附加变量在本题中记录遍历到该结点形成的字符串出现的次数,在不同题中可记录不同的内容。 Treenode *next[kind];//指向儿子结点 Treenode()//每个结点的初始化 { count = 1; for(int i=0;i<kind;i++) next[i]=NULL; } }; void insert(Treenode *&root,char *word)//向以root为根结点的树中插入串word { Treenode *location=root; int i=0,branch=0; if(location==NULL) {location=new Treenode();root=location;} while(word[i]) { branch=word[i]-'a'; if(!location->next[branch]) location->next[branch]=new Treenode();//如果不存在,建新结点 else location->next[branch]->count++; i++; location=location->next[branch]; } } int search(Treenode* location, char* word) { int i=0, branch; while (word[i]) { branch = word[i] - 'a'; if (location->next[branch] == NULL) return 0; location = location->next[branch]; i++; } return location->count; } int main() { char tmp; int i, j, len, curcount; bool last; Treenode* root = NULL, *location; //freopen("data.txt", "r", stdin); i = 0; while (scanf("%s", str[i]) != EOF) { insert(root, str[i]); i++; } n = i; for (i=0; i<n; i++) { printf("%s ", str[i]); len = strlen(str[i]); for (j=len-1; j>=-1; j--) { tmp = str[i][j+1]; str[i][j+1] = 0; curcount = search(root, str[i]); if (curcount>1 || j==-1) { str[i][j+1] = tmp; printf("%s", str[i]); break; } } printf("/n"); } return 0; }

你可能感兴趣的:(pku2001 Shortest Prefixes (trie))