POJ 2001:Shortest Prefixes(字典树)

来源:互联网 发布:深入浅出数据分析笔记 编辑:程序博客网 时间:2021/11/29 07:51

Shortest Prefixes
Time Limit: 1000MS Memory Limit: 30000KTotal Submissions: 7290 Accepted: 3054


A prefix of a string is a substring starting at the beginning of the given string. The prefixes of "carbon" are: "c", "ca", "car", "carb", "carbo", and "carbon". Note that the empty string is not considered a prefix in this problem, but every non-empty string is considered to be a prefix of itself. In everyday language, we tend to abbreviate words by prefixes. For example, "carbohydrate" is commonly abbreviated by "carb". In this problem, given a set of words, you will find for each word the shortest prefix that uniquely identifies the word it represents. 

In the sample input below, "carbohydrate" can be abbreviated to "carboh", but it cannot be abbreviated to "carbo" (or anything shorter) because there are other words in the list that begin with "carbo". 

An exact match will override a prefix match. For example, the prefix "car" matches the given word "car" exactly. Therefore, it is understood without ambiguity that "car" is an abbreviation for "car" , not for "carriage" or any of the other words in the list that begins with "car". 


The input contains at least two, but no more than 1000 lines. Each line contains one word consisting of 1 to 20 lower case letters.


The output contains the same number of lines as the input. Each line of the output contains the word from the corresponding line of the input, followed by one blank space, and the shortest prefix that uniquely (without ambiguity) identifies this word.

Sample Input


Sample Output

carbohydrate carbohcart cartcarburetor carbucaramel caracaribou caricarbonic carbonicartilage carticarbon carboncarriage carrcarton cartocar carcarbonate carbona

#include<iostream>using namespace std;const int MAX=26;typedef struct TrieNode  //结点{int nCount;      //记录该字符出现次数struct TrieNode *next[MAX];}TrieNode;TrieNode Memory[1000000];int allocp=0;void InitTrie(TrieNode **pRoot)//初始化{*pRoot=NULL;}TrieNode *CreateTrieNode()//创建新结点{TrieNode *p;p=&Memory[allocp++];p->nCount=1;for(int i=0;i<MAX;i++){p->next[i]=NULL;}return p;}//插入void InsertTrie(TrieNode **pRoot,char s[]){TrieNode *p;if(!(p=*pRoot)){p=*pRoot=CreateTrieNode();}int i=0;while(s[i]){int k=s[i++]-'a';if(p->next[k]==NULL)p->next[k]=CreateTrieNode();elsep->next[k]->nCount++;p=p->next[k];}}int SearchTrie(TrieNode **pRoot,char s[]){if(*pRoot==NULL) return 0;TrieNode *p=*pRoot;int i=0;while(s[i]){int k=s[i++]-'a';if(p->next[k]==NULL) return 0;p=p->next[k];}return p->nCount;}int SelectPre(TrieNode **pRoot,char s[]) //这道题目变形一下{TrieNode *p=*pRoot;int i=0;while(s[i]){int k=s[i++]-'a';if(p->next[k]->nCount==1) return i;p=p->next[k];}return i; //返回最后}int main(){int i,j,n=0;TrieNode *root;InitTrie(&root);char s[1005][25];while(cin>>s[n]){InsertTrie(&root,s[n]);n++;}for(i=0;i<n;i++){j=SelectPre(&root,s[i]);cout<<s[i]<<" ";for(int k=0;k<j;k++)cout<<s[i][k];cout<<endl;}return 0;}