(trie) Shortest Prefixs(P2001)

来源:互联网 发布:马尔科夫矩阵怎么算 编辑:程序博客网 时间:2024/06/10 04:01

这个自己写的,要注意新开一个指针得用new,



#include<iostream>#include<cstdio>#include<algorithm>#include<queue>#include<vector>#include<cmath>#include<set>#include<cstring>using namespace std;#define N 26struct tree{int num;tree* next[N];tree(){num=1;memset(next,NULL,sizeof(next));}}*t;char hi[1001][30];void create(tree *tt,char *go){int i,j,k;tree *cur ;if (!*go)return ;k=*go-'a';cur=tt->next[k];//cout<<"yes";if (cur==NULL){//cout<<"1";cur=new tree;tt->next[k]=cur;create(cur,go+1);}else{//cout<<"2";cur->num++;create(cur,go+1);}}void put(tree *tt,char *go,bool f){//cout<<*go<<endl;int i,j,k;if (!*go||tt==NULL)return ;//cout<<"yes";k=*go-'a';tree *cur = tt->next[k];if (cur->num==1){printf("%c",*go);}else{printf("%c",*go);put(cur,go+1,false);}}int main(){freopen("in.txt","r",stdin);int i,j,k;char go[111];//t= new tree;t=new tree;int n=0;while (cin>>hi[n]){create(t,hi[n]);n++;}for (i=0;i<n;i++){printf("%s ",hi[i]);put(t,hi[i],true);printf("\n");}return 0;}


Shortest Prefixes
Time Limit: 1000MS Memory Limit: 30000KTotal Submissions: 9212 Accepted: 3912

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.

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".

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

carbohydratecartcarburetorcaramelcariboucarboniccartilagecarboncarriagecartoncarcarbonate

Sample Output

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

Source



原创粉丝点击