您的位置:首页 > 其它

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;
}


先建树,再查找,一边查找一遍输出即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: