Shortest Prefixes
Time Limit: 1000MS |
|
Memory Limit: 30000K |
Total Submissions: 14747 |
|
Accepted: 6364 |
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
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
第一道字典树:0ms
#include <cstdio>
#include <cstring>
#define MAX 10000+10
using namespace std;
char str[1010][30];
int ch[MAX][30];
int word[MAX];//记录当前节点下有几个单词
int n = 0;//单词个数
int sz;//节点数
void init()
{
sz = 1;//只有一个根节点
memset(ch[0], 0 ,sizeof(ch[0]));
memset(word, 0, sizeof(word));
}
int idx(char x)//字母编号
{
return x-'a';
}
void insert(char *s)//插入
{
int i, j, l = strlen(s);
int u = 0;
for(i = 0; i < l; i++)
{
int c = idx(s[i]);
if(!ch[u][c])//节点不存在
{
memset(ch[sz], 0, sizeof(sz));//初始化新节点
ch[u][c] = sz;
sz++; //节点数自增一
}
u = ch[u][c];
word[u]++;//单词数加一
}
}
void find(char *s)//查询
{
int i, j, l = strlen(s);
int u = 0;//从根节点开始
for(i = 0; i < l; i++)
{
int c = idx(s[i]);
u = ch[u][c];
printf("%c", s[i]);
if(word[u] == 1)//当前前缀足以找出单词
return ;
}
}
int main()
{
init();
while(scanf("%s", str[n]) != EOF)
{
insert(str[n]);//插入
n++;
}
for(int i = 0; i < n; i++)
{
printf("%s ", str[i]);
find(str[i]);
printf("\n");
}
return 0;
}