Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 12731 | Accepted: 5442 |
Description
Input
Output
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
Source
1 #include <iostream>
2 #include <stdio.h>
3 #include <string.h>
4 using namespace std; 5
6 struct Tire{ 7 Tire *next[26]; 8 int num; //记录以当前字符串为前缀的单词的数量
9 Tire() //构造函数初始化
10 { 11 int i; 12 for(i=0;i<26;i++) 13 next[i]=NULL; 14 num=0; 15 } 16 }; 17 Tire root; 18 char word[1001][21]; //字典
19
20 void Insert(char word[]) //将单词word插入到字典树中
21 { 22 Tire *p = &root; 23 int i; 24 for(i=0;word[i];i++){ 25 int t = word[i] - 'a'; 26 if(p->next[t]==NULL) 27 p->next[t]=new Tire; 28 p = p->next[t]; 29 p->num++; 30 } 31 } 32
33 void Find(char word[]) //找到单词word的最短唯一前缀并输出(假设一定存在,即查找num=1的位置,输出字符串)
34 { 35 Tire *p = &root; 36 int i; 37 for(i=0;word[i];i++){ 38 int t = word[i]-'a'; 39 if(p->next[t]==NULL) 40 return ; 41 p = p->next[t]; 42 printf("%c",word[i]); 43 if(p->num==1) 44 return; 45 } 46 } 47
48 int main() 49 { 50 int size=1,i; //字典大小
51 while(scanf("%s",word[size])!=EOF){ 52 //if(word[size][0]=='0') break;
53 Insert(word[size++]); 54 } 55 size--; 56 for(i=1;i<=size;i++){ //查找每一个单词的最短唯一前缀
57 printf("%s ",word[i]); 58 Find(word[i]); 59 printf("\n"); 60 } 61 return 0; 62 }
Freecode : www.cnblogs.com/yym2013