Description
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.Input
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.Output
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
carbohydrate cart carburetor caramel caribou carbonic cartilage carbon carriage carton car carbonate
Sample Output
carbohydrate carboh cart cart carburetor carbu caramel cara caribou cari carbonic carboni cartilage carti carbon carbon carriage carr carton carto car car carbonate carbona
Source
Rocky Mountain 2004#include#include #include #include const int MAX = 27 ; const int MAXS = 21 ; const int MAXN = 1005 ; struct trie{ int point; trie *next[MAX]; }; trie *root=new trie; char str[MAXN][MAXS]; int number=0; void createTrie(char *s){ trie *p=root,*q; int len=strlen(s),pos; for(int i=0;i next[pos]==NULL){ q=new trie; q->point=1; for(int j=0;j next[j]=NULL; p->next[pos]=q; p=p->next[pos]; } else{ p->next[pos]->point++; p=p->next[pos]; } } } void findTrie(char *s){ trie *p=root; int len=strlen(s),pos; for(int i=0;i next[pos]->point==1) break; p=p->next[pos]; } printf("\n"); } void delTrie(trie *Root){ for(int i=0;i next[i]!=NULL) delTrie(Root->next[i]); } free(Root); } int main(){ //freopen("liuchu.txt","r",stdin); for(int i=0;i next[i]=NULL; while(scanf("%s",str[number])!=EOF){ createTrie(str[number]); number++; } for(int i=0;i