zoj 1109 Language of FatMouse 【字典樹】

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


發佈了164 篇原創文章 · 獲贊 1 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章