POJ 2503-Babelfish【字典树】

Babelfish
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 39270   Accepted: 16778

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.

Source

Waterloo local 2001.09.22

解题思路:

主要是空哪一行有点坑。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char word[100100][12];
typedef struct node
{
	int cnt;
	node *next[26];
}Trie;
Trie root;
void ct(char *str,int jj)
{
	//printf("%d\n",jj);
	int len,i,j;
	len=strlen(str);
	Trie *p=&root,*q;
	for(i=0;i<len;i++)
	{
		int id=str[i]-'a';
		if(p->next[id]==NULL)
		{
			q=new Trie;
			if(i==len-1)
			{
				q->cnt=jj;
			}
			for(j=0;j<26;j++)
			 	q->next[j]=NULL;
			p->next[id]=q;
			
			p=p->next[id];
		}
		else
		{
			if(i==len-1)
			{
				p->next[id]->cnt=jj;
			}
			p=p->next[id];
		}
	}
}
int find(char *str)
{
	int len,i,j,id;
	len=strlen(str);
	Trie *p=&root;
	for(i=0;i<len;i++)
	{
		id=str[i]-'a';
		if(p->next[id]==NULL)
		return -1;
		//printf("%d\n",p->next[id]->cnt);
		if(i==len-1)
		{
			return p->next[id]->cnt; 
		}
		p=p->next[id];
	}
	return -1;
}
int main()
{
	char hh[15];
	char map[15];
	int io=0;
	while(true)
	{
		char t;
		if((t=getchar())=='\n')  
			break;
		else     
		{
			map[0]=t;
			int i=1;
			while(true)
			{
				t=getchar();
				if(t==' ')
				{
					map[i]='\0';
					break;
				}
				else
					map[i++]=t;
			}
		}
		strcpy(word[io++],map);
		scanf("%s",hh);
		ct(hh,io-1);
		getchar();
	}
	while(scanf("%s",hh)!=EOF)
	{
		int xx=find(hh);
		//printf("%d\n",xx);
		if(xx==-1)
		{
			printf("eh\n");
		}
		else
		{
			printf("%s\n",word[xx]);
		}
	}
	return 0;
 } 


你可能感兴趣的:(poj,字典树)