POJ_2503_Babelfish【字典树】

Babelfish
Time Limit: 3000MS
Memory Limit: 65536K
Total Submissions: 43623
Accepted: 18403

Description

You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.

Input

Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.

Output

Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".

Sample Input

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

Sample Output

cat
eh
loops

Hint

Huge input and output,scanf and printf are recommended.

字典树

又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。

基本操作
查找、插入和删除

性质

它有3个基本性质:
根节点不包含字符,除根节点外每一个节点都只包含一个字符; 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串; 每个节点的所有子节点包含的字符都不相同。

基本操作
其基本操作有:查找、插入和删除,当然删除操作比较少见。

实现方法
搜索字典项目的方法为:
(1) 从根结点开始一次搜索;
(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;
(3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。
(4) 迭代过程……
(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。
其他操作类似处理


题意:前面一组数据是英问和火星文对应的译码表  接着输入的是火星文,
要求根据译码表吧火星文翻译成英文,如果找不到则输出 eh
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
	char low[11];
	Node *next[26];
};
Node *root,*p,*q;
void Init(Node *root)
{
	root->low[0]='#';
	for(int i=0;i<26;i++)
		root->next[i]=NULL;
}
void BuildTire(char *s2,char *s1)
{
	int i,v;
	for(i=0,p=root;i<strlen(s2);i++)
	{
		v=s2[i]-'a';
		if(p->next[v]==NULL)
		{
			q=(struct Node*)malloc(sizeof(Node));
			Init(q);
			p->next[v]=q;
		}
		p=p->next[v];
	}
	strcpy(p->low,s1);
}
Node *Insearch(char *str)
{
	int i,v;
	for(i=0,p=root;i<strlen(str);i++)
	{
		v=str[i]-'a';
		if(p->next[v]==NULL)
			break;
		p=p->next[v];
	}
	return p;
}
int main()
{
	char str[23],s1[11],s2[11];
	root=(struct Node *)malloc(sizeof(Node));
	Init(root);
	while(gets(str) && str[0]!='\0')//以回车结束 
	{
		sscanf(str,"%s%s",s1,s2);//格式话字符串 
		BuildTire(s2,s1);
	}
	while(gets(str) && str[0]!='\0')
	{
		Node *r=Insearch(str);
		if(r->low[0]!='#')
			printf("%s\n",p->low);
		else
			printf("eh\n");
	}
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章