zoj 1109 Language of FatMouse 【字典树】

94 篇文章 0 订阅
2 篇文章 0 订阅
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct __TrieNode
{
	char value;
	char * word;
	struct __TrieNode * next;
	struct __TrieNode * son;
};
typedef __TrieNode node;
char s[100009][11];
node m[1000000];
int cnt, cnts, step=0;
void fillNode(int n, char value, char * word, node * next, node * son)
{
	m[n].value = value;
	m[n].word = word;
	m[n].next = next;
	m[n].son = son;
}
void init()
{
	cnt = 0;
	cnts = -1;
	fillNode(cnt, '\a', NULL, NULL, &m[1]); //根节点 
	cnt++;
	fillNode(cnt, '\0', NULL, NULL, NULL);	//根节点的子节点 
}
void addNode(char * s, int pos)
{
	int i;
	node * pnow = &m[0];
	for(i=pos+1; i<strlen(s); i++)
	{
		pnow = pnow->son;
		while(pnow->next != NULL && pnow->next->value < s[i])
			pnow = pnow->next;
			
		if(pnow->next == NULL)
		{
			cnt++;
			fillNode(cnt, '\0', NULL, NULL, NULL);
			cnt++;
			fillNode(cnt, s[i], NULL, NULL, &m[cnt-1]);
			pnow->next = &m[cnt];
			pnow = pnow->next;
			continue;
		}
	
		if(pnow->next->value == s[i]){
			pnow = pnow->next;
			continue;
		}
		if(pnow->next->value > s[i])
		{
			cnt++;
			fillNode(cnt, '\0', NULL, NULL, NULL);
			cnt++;
			fillNode(cnt, s[i], NULL, pnow->next, &m[cnt-1]);
			pnow->next = &m[cnt];
			pnow = pnow->next;
			continue;
		}
	}
	pnow->word = s;
}
void find(char * s)
{
	int i;
	node * next = &m[0];
	for(i=0; i<strlen(s); i++)
	{
		next = next->son;
		while(next != NULL && next->value != s[i])
			next = next->next;
		if(next == NULL)
			break;
	}
	if(next == NULL)
	{
		printf("eh\n");
		return;
	}
	for(i=0; (next->word)[i]!=' '; i++)
		printf("%c", (next->word)[i]);
	printf("\n");
}
int findSpace(char *s)
{
	int i;
	for(i=0; i<strlen(s); i++)
		if(s[i] == ' ')
			return i;
	return 0;
}
int main()
{
	int pos;
	init();
	while( gets(s[++cnts]) )
	{
		if(pos = findSpace(s[cnts]) )
			addNode(s[cnts], pos);
		else
			break;
	}
	cnts++;
	while( gets(s[cnts]) )
		find( s[cnts] );
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值