题目描述
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
题目链接
http://poj.org/problem?id=2001
解题思路
还是比较容易想到的,就是一个简单的字典树。首先把所有的单词全都存入字典树,然后一个一个的搜索,搜索到1为止,证明这个时候已经找到了他自己独一无二的前缀了;假如没有搜到1,就直接输出整个单词即可,因为搜不到1证明它自己就是一个前缀。(开数组的时候要小心,不要因为简单就随便,第一发竟然MLE了= =)
AC代码
1612K/79MS/G++1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
int ch[10005][30], sz, val[10005];
void init()
{
sz = 1;
memset(ch, 0, sizeof(ch));
memset(val, 0, sizeof(val));
}
void insertion(char *s)
{
int u = 0, i, c, len = strlen(s);
for (i = 0; i < len; i++)
{
c = s[i] - 'a';
if (!ch[u][c])
{
ch[u][c] = sz;
sz++;
}
u = ch[u][c];
val[u]++;
}
}
int query(char *s)
{
int u = 0, i, c, l = strlen(s);
for (i = 0; i < l; i++)
{
c = s[i] - 'a';
if (!ch[u][c]) return 0;
u = ch[u][c];
if (val[u] == 1)
return i + 1;
}
return l;
}
char str[1005][25];
int main()
{
int index = 0;
init();
while (~scanf("%s", str[index]))
{
insertion(str[index]);
index++;
}
for (int i = 0; i < index; i++)
{
int len = query(str[i]);
printf("%s ", str[i]);
for (int j = 0; j < len; j++)
{
printf("%c", str[i][j]);
}
printf("\n");
}
return 0;
}