poj 2001 Shortest Prefixes ——字典树入门
2013-02-26 23:29
495 查看
题目链接:http://poj.org/problem?id=2001 题目大意: 给一系列单词,找出么每个单词的最小缩写,使得这些缩写不出现歧义。还有,完全相同的优先级比前缀的优先级高,意思就是,如果一个单词的缩写就是这个单词本身,那么它不能代表以它为前缀的单词,而仅仅代表它本身。 题目思路: 第一道字典树题目,写代码还是要认真,出一些写错误是最吃亏的。减少错误的办法就是,第一,多敲代码,敲熟练一点儿,孰能生巧。第二,写代码的过程中要养成习惯,就是先把问题想透彻,再写,一边写一边思考。
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; char a[1000+10][25]; const int sonnum = 26, base = 'a'; struct Trie { int num; bool terminal; struct Trie *son[sonnum]; }; Trie *NewTrie() { Trie *temp = new Trie; temp->num = 1; temp->terminal = false; for (int i = 0; i < sonnum; ++i) temp->son[i] = NULL; return temp; } void Insert(Trie *pnt, char *s, int len) { Trie *temp = pnt; for (int i = 0; i < len; ++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; } Trie *Find(Trie *pnt, char *s, int len) { Trie *temp = pnt; for (int i = 0; i < len; ++i) { if (temp->son[s[i]-base]->num == 1) { printf("%c", s[i]); return temp; } printf("%c", s[i]); temp = temp->son[s[i]-base]; } return temp; } int main(void) { #ifndef ONLINE_JUDGE freopen("poj2001.in", "r", stdin); #endif int cnt = 0; Trie *tree = NewTrie(); while (~scanf("%s", a[cnt])) { Insert(tree, a[cnt], strlen(a[cnt])); cnt++; } for (int i = 0; i < cnt; ++i) { printf("%s ", a[i]); Find(tree, a[i], strlen(a[i])); printf("\n"); } return 0; }
先建树,再查找,一边查找一遍输出即可。
相关文章推荐
- POJ 2001 Shortest Prefixes 字典树
- poj 2001 Shortest Prefixes 字典树
- Shortest Prefixes POJ - 2001 (字典树模板题~)
- POJ 2001 Shortest Prefixes【第一棵字典树】
- poj 2001 Shortest Prefixes 【字典树】【找每一个字符串在字符串集里面的 最短且可唯一标识 的前缀】
- [字典树] poj 2001 Shortest Prefixes
- POJ 2001 Shortest Prefixes 【 trie树(别名字典树)】
- 字典树---2001 POJ Shortest Prefixes(找最短前缀)
- 字典树---2001 POJ Shortest Prefixes(找最短前缀)
- [复习][poj2001]字典树(trie树)Shortest Prefixes
- poj 2001 Shortest Prefixes 字典树的输出问题的解释~~ 2012-4-14
- POJ 2001 Shortest Prefixes 【 trie树(别名字典树)】
- POJ 2001 Shortest Prefixes 字典树Trie
- 【POJ 2001 Shortest Prefixes】+ 字典树
- POJ 2001 Shortest Prefixes【字典树】
- POJ 2001-Shortest Prefixes【字典树】
- POJ 2001 Shortest Prefixes 字典树经典题,求最短唯一前缀)
- POJ 2001 Shortest Prefixes【字典树】
- poj 2001 Shortest Prefixes 字典树
- POJ【2001】Shortest Prefixes----字典树