HDU ACM 1075 What Are You Talking About(字典树)
http://acm.hdu.edu.cn/showproblem.php?pid=1075
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 struct Node 5 { 6 char str[20]; 7 int flag; 8 Node *child[26]; 9 }; 10 void NewNode(Node **Q)//注意这里使用了指针的指针 11 { 12 (*Q) = (Node *)malloc(sizeof(Node)); 13 int i; 14 for(i=0;i<26;i++) 15 { 16 (*Q)->child[i] = NULL; 17 } 18 } 19 void Insert(Node **T,char str[],char set[])//注意这里使用了指针的指针 20 { 21 Node *Q = *T; 22 int len = strlen(str); 23 int i; 24 for(i=0;i<len;i++) 25 { 26 if(Q->child[str[i] - 'a'] != NULL) 27 { 28 Q = Q->child[str[i] - 'a']; 29 } 30 else 31 { 32 NewNode(&(Q->child[str[i] - 'a'])); 33 Q = Q->child[str[i] - 'a']; 34 } 35 } 36 Q->flag = 1; 37 strcpy(Q->str,set); 38 } 39 40 void Search(Node *Q,char str[]) 41 { 42 int len = strlen(str); 43 if(len == 0) 44 { 45 return ; 46 } 47 int i; 48 for(i=0;i<len;i++) 49 { 50 if(Q->child[str[i] - 'a'] != NULL) 51 { 52 Q = Q->child[str[i] - 'a']; 53 } 54 else 55 { 56 break; 57 } 58 } 59 if(Q->flag == 1 && i == len) 60 { 61 cout<<Q->str; 62 } 63 else 64 { 65 cout<<str; 66 } 67 } 68 int main() 69 { 70 char str[3100]; 71 Node *T = NULL; 72 NewNode(&T); 73 int flag = 0; 74 cin>>str; 75 getchar(); 76 while(1) 77 { 78 gets(str); 79 if( strcmp(str,"END") == 0 ) 80 { 81 break; 82 } 83 else 84 { 85 int i,j; 86 char english[20] = {0}; 87 char mars[20] = {0}; 88 for(i=0;1;i++) 89 { 90 if(str[i] >= 'a' && str[i]<='z') 91 { 92 english[i] = str[i]; 93 } 94 else 95 { 96 english[i] = 0; 97 break; 98 } 99 } 100 for(i=i+1,j=0;1;i++,j++) 101 { 102 if(str[i] >= 'a' && str[i]<='z') 103 { 104 mars[j] = str[i]; 105 } 106 else 107 { 108 mars[j] = 0; 109 break; 110 } 111 } 112 Insert(&T,mars,english); 113 } 114 } 115 cin>>str; 116 getchar(); 117 while(1) 118 { 119 gets(str); 120 if( strcmp(str,"END") == 0 ) 121 { 122 break; 123 } 124 else 125 { 126 int len = strlen(str); 127 char mid[20] = {0}; 128 int i,j; 129 for(i=0,j=0;i<len;i++) 130 { 131 if(str[i] >= 'a' && str[i]<='z') 132 { 133 mid[j] = str[i]; 134 j++; 135 } 136 else 137 { 138 mid[j] = 0; 139 j=0; 140 Search(T,mid); 141 cout<<str[i]; 142 } 143 } 144 if(mid[0] != 0) 145 { 146 mid[j] = 0; 147 Search(T,mid); 148 } 149 cout<<endl; 150 } 151 } 152 return 0; 153 } 154 155 /* 156 START 157 from fiwo 158 hello difh 159 mars riwosf 160 earth fnnvk 161 like fiiwj 162 END 163 START 164 difh 165 */