Shortest Prefixes

来源:互联网 发布:java中object类的方法 编辑:程序博客网 时间:2024/05/21 10:42
A - Shortest Prefixes
Time Limit:1000MS     Memory Limit:30000KB     64bit IO Format:%I64d & %I64u
Submit Status

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
AC代码:
#include<iostream>#include<cstring>#include<string>using namespace std;struct trie{string str;int cnt;trie* kid[26];trie(){cnt=0;str="";for(int i=0;i<26;++i){kid[i]=NULL;}}}*root;void insert(string str){trie* t=root;for(int i=0;str[i];++i){int d=str[i]-'a';if(t->kid[d]==NULL){t->kid[d] = new trie;t->kid[d]->str=t->str+str[i];}t=t->kid[d];t->cnt++;}}string find(string str){trie* t=root;for(int i=0;str[i];++i){int d = str[i] - 'a';if(t->cnt==1){return t->str;}t = t->kid[d];}return t->str;}int main(){/*freopen("input.txt","r",stdin);*/string str[1100];root = new trie;int cnt=0;while(cin >> str[cnt]){insert(str[cnt++]);}for(int i=0;i<cnt;++i){cout << str[i] << " ";cout << find(str[i]) << endl;}return 0;}


0 0
原创粉丝点击