1. 程式人生 > >POJ 2503 Babelfish(字典樹)

POJ 2503 Babelfish(字典樹)

題意:每個單詞對應一個單詞,然後輸入n個單詞,輸出對應的單詞。

題解:map能解決,排序+二分也能,字典樹也能。水題

程式碼:

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;

const int maxn = 26;
typedef struct TrieNode{
	char str[14];
	bool isWord;
	struct TrieNode *son[maxn];
}Trie;

void insertWord(Trie *root,char word[],char str[]){
	Trie *p = root;
	int i = 0;
	char ch = word[i];
	while(ch != '\0'){
		if(p->son[ch-'a'] == NULL){
			Trie *node =(Trie*)malloc(sizeof(Trie));
			for(int i = 0 ; i < maxn ; i ++){
				node->son[i] = NULL;
			}
			node->isWord = false;
			p->son[ch-'a'] = node;
			p = p->son[ch-'a'];
		}
		else {
			p = p->son[ch-'a'];
		}
		ch = word[++i];
	}
	p->isWord =true;
	strcpy(p->str,str);
}

void findWord(Trie *root,char word[]){
	int i = 0 ;
	char ch = word[i];
	Trie *p = root;
	while(p != NULL && ch != '\0'){
		p = p->son[ch -'a'];
		ch = word[++i];
	}
	if(p == NULL) printf("eh\n");
	else if(p->isWord == false) printf("eh\n");
	else printf("%s\n",p->str);
}


int main(){
	Trie *root = (Trie*)malloc(sizeof(Trie));
	for(int i = 0 ; i < maxn ; i ++){
		root->son[i] = NULL;
	}
	char str1[12],str2[12],str[50];
	while(gets(str)){
		if(strlen(str) == 0) break;
		sscanf(str,"%s %s",str1,str2);
		insertWord(root,str2,str1);
	}
	while(gets(str2)){
		findWord(root,str2);
	}
	return 0;
}