您的位置:首页 > 其它

zoj 1109 Language of FatMouse(字典树Trie)

2010-12-24 23:35 429 查看
这个应该算是字典树的经典应用了吧。



讲需要查找的内容存进字典树里~然后查找这个单词,就能把所存的data给调出来~



详情见大牛BLOG http://www.cnblogs.com/DreamUp/archive/2010/07/23/1783410.html


我的函数都是自己写的哦~~~嘻嘻~~~



WA了数次。因为node数组开小了,如果用malloc就不会出现这种情况了。。。可我不喜欢malloc。。。



我的node数组是从里面拿空间用的。



#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#define MAX 100006
using namespace std;
typedef struct Trie{
	Trie *child[26];
	int data;
}Trie;
Trie node[120000];  // I hate it!!! The size of the node should biger than 100006 = =. WA N times.
int cou;
void init()
{
	cou = 1;
	memset(node,'/0',sizeof(node));
}
void Build( char *a, int num)  //Build the trie, magic ~
{
	Trie *head = &node[0];
	int len = strlen(a);
	for(int i=0; i<len; i++)
	{
		if( head->child[a[i]-'a'] == NULL )
			head->child[a[i]-'a'] = &node[cou++];
		head = head->child[a[i]-'a'];
	}
	head->data = num;
}
int Find( char *a )  // Find the data in the trie.
{
	Trie *head = &node[0];
	int len = strlen(a);
	for(int i=0; i<len; i++)
	{
		head = head->child[a[i]-'a'];
		if( head == NULL )  
			return 0;
	}
	return head->data;
}
char eng[MAX][50],mice[MAX][50];
char tofind[50];
char str[50];
int main(void)
{
	int count = 1;
	init();
	while( gets(str) && strlen(str) )
	{
		sscanf(str,"%s%s",eng[count],mice[count]); // = = . Fire station 's input format...
		count++;
	}	
	for( int i=1; i<count; i++ )
		Build( mice[i], i );
	while( scanf("%s",tofind) != EOF )
	{
		int ind = Find( tofind );
		if( ind == 0 )
			printf("eh/n");
		else
			printf("%s/n",eng[ind]);
	}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: