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".
carbohydrate cart carburetor caramel caribou carbonic cartilage carbon carriage carton car carbonate
carbohydrate carboh cart cart carburetor carbu caramel cara caribou cari carbonic carboni cartilage carti carbon carbon carriage carr carton carto car car carbonate carbona
字典树模板题~ 用了静态数组的方法
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
struct Trie {
int value;
int child[26]; // 子节点最多有26个(小写字母或大写字母)
Trie() { //构造函数
value = 0;
memset(child, 0, sizeof(child));
}
}trie[3100];
int trieN = 0;
void insert(char str[]) {
int x = 0;
for (int i = 0; str[i]; i++) {
int d = str[i] - 'a';
if (trie[x].child[d] == NULL) { // 如果该节点没有子树
trie[++trieN] = Trie();
trie[x].child[d] = trieN;
}
x = trie[x].child[d];
trie[x].value++;
}
}
void search(char str[]) {
int x = 0, len = strlen(str);
for (int i = 0; i < len; i++) {
if (trie[x].value == 1) break;
int d = str[i] - 'a';
cout << str[i];
//cout << trie[x].value;
x = trie[x].child[d];
}
}
int main(void) {
//freopen("in.txt", "r", stdin);
char s[3010][26];
int cnt = 0;
while (~scanf("%s", s[cnt])) {
//cout << s[cnt] << endl;
insert(s[cnt]);
cnt++;
}
for (int i = 0; i < cnt; i++) {
printf("%s ", s[i]);
search(s[i]);
cout << endl;
}
return 0;
}