此题用map也可过,我用的是线段树
传送门:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1109
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxn 30
struct Trie{
Trie * next[maxn];
char * english;
};
Trie * root;
char a[100050][15];
void Init_Trie(){
root = (Trie *)malloc(sizeof(Trie));
for(int i=0;i<maxn;i++){
root -> next[i] = NULL;
}
}
void Add_Trie(char * lish,char * str){
Trie * p = root , * q;
for(int i=0;str[i]!='\0';i++){
int id = str[i] - 'a';
if(p->next[id]==NULL){
q = (Trie *)malloc(sizeof(Trie));
q -> english = NULL;
for(int j=0;j<maxn;j++){
q -> next[j] = NULL;
}
p -> next[id] = q;
p = p -> next[id];
}
else {
p = p -> next[id];
}
}
p -> english = lish;
}
char * Search_Trie(char * str){
Trie * p = root;
for(int i=0;str[i]!='\0';i++){
int id = str[i] - 'a';
p = p -> next[id];
if(p==NULL){
return NULL;
}
}
return p->english;
}
void Del_Trie(Trie * p){
for(int i=0;i<maxn;i++){
if(p->next[i])Del_Trie(p->next[i]);
}
free(p);
}
void Input(){
int k = 0;
char tempb[15];
char tempab[45];
Init_Trie();
while(gets(tempab),tempab[0]!='\0'){
sscanf(tempab,"%s %s",a[k++],tempb);
Add_Trie(a[k-1],tempb);
}
while(gets(tempb)){
char * ans = Search_Trie(tempb);
if(ans==NULL){
puts("eh");
}
else
puts(ans);
}
Del_Trie(root);
}
void File(){
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
}
int main(void){
//File();
Input();
return 0;
}