POJ2001 Shortest Prefixes【字典树】

来源:互联网 发布:汽车租赁源码 编辑:程序博客网 时间:2024/05/17 07:09

题目链接:

http://poj.org/problem?id=2001


题目大意:

给一些字符串,求出每个字符串在这些字符串中能可以被唯一识别的最小前缀。


思路:

字典树的模板题,结构体中庸Count来存储字符前缀出现的次数,字典树中找到第一个

Count为1的前缀时,该前缀就是被唯一识别的最小前缀。


AC代码:

#include<iostream>#include<algorithm>#include<cstdio>#include<cstring>using namespace std;struct TrieNode{int Count;struct TrieNode *Next[26];};TrieNode *root;void Create(){root = new TrieNode;memset(root->Next,NULL,sizeof(root->Next));root->Count = 0;}void Insert(char *s){TrieNode *p, *q;p = root;while(*s){if(p->Next[*s-'a'] == NULL){q = new TrieNode;memset(q->Next,NULL,sizeof(q->Next));q->Count = 1;p->Next[*s-'a'] = q;}elsep->Next[*s-'a']->Count++;p = p->Next[*s-'a'];s++;}}void Find(char *s){TrieNode *p, *q;p = root;while(*s){if(p->Count == 1)break;printf("%c",*s);p = p->Next[*s-'a'];s++;}printf("\n");}char word[1100][22];int main(){int k = 0;Create();while(scanf("%s",word[k]) != EOF){Insert(word[k]);k++;}for(int i = 0; i < k; ++i){printf("%s ",word[i]);Find(word[i]);}return 0;}


0 0