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;
}




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