POJ 2503 Babelfish(字典树)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/PK__PK/article/details/82784461

题目连接:http://poj.org/problem?id=2503

题意:每个单词对应一个单词,然后输入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;
}

猜你喜欢

转载自blog.csdn.net/PK__PK/article/details/82784461
今日推荐