uva 10282 Trie樹

 字典樹是哈希樹的一種,通常用於字符串匹配,由於思想和實現都很簡單,所以我就不再介紹了,自己google之吧。。

很水的題,RE了一次,好吧我現在太浮躁了...

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define CLR(array,val) memset(array,val,sizeof(array))
#define MAX 26
using namespace std;

typedef struct Trie_tree
{
	struct Trie_tree * next[MAX];
	int v;
}Trie;
Trie * root;
char word[300000][200];
void initTrie( )
{
	root = (Trie*)malloc(sizeof(Trie));
	root->v = -1;
	for( int i = 0; i < MAX; i++ )
		root->next[i] = NULL;
};
void createTrie( char *str, int num )
{
	int len = strlen(str);
	Trie *p = root;
	Trie *q;
	for( int i = 0; i < len; i++ )
	{
		int id = str[i] - 'a';
		if( p->next[id] == NULL )
		{
			q = (Trie*)malloc(sizeof(Trie)); 
			q->v = -1;
			for( int j = 0; j < MAX; j++ )
				q->next[j] = NULL;
			p->next[id] = q;
			p = p->next[id];
		}
		else
			p = p->next[id];
	}
	p->v = num;
};
int findTrie( char *str )
{
	Trie * p = root;
	int len = strlen(str);
	for( int i = 0; i < len; i++ )
	{
		int id = str[i]-'a';
		p = p->next[id];
		if( p == NULL )
			return -1;
	}
	if( p->v != -1 )
		return p->v;
	return -1;
};
void delTrie( Trie * root )
{
	if( root == NULL )
		return ;
	for( int i = 0; i < MAX; i++ )
	{
		if( root->next[i] != NULL )
			delTrie( root->next[i] );
	}
	free( root );
	return ;
};
int main()
{
	int i = 0, flag, t = 0;
	char temp[200];
	char temp1[2][200];
	char temp3[200];
	initTrie( );
	while( gets( temp ) )
	{
		int len = strlen( temp );
		if( len == 0 ) break;
		for( int i = 0, j = 0, a = 0; i < len; i++ )
		{
			if( islower(temp[i]) )
			{
				temp1[j][a++] = temp[i];
				temp1[j][a] = '\0';
			}
			if( temp[i] == ' ' )
			{
				a = 0;
				j = 1;
				continue;
			}
		}
		createTrie( temp1[1], t );
		strcpy( word[t], temp1[0] );
		t++;
	}
	while( scanf( "%s", temp3 ) != EOF )
	{
		flag = findTrie( temp3 );
		if( flag == -1 )
			printf( "eh\n" );
		else
			printf( "%s\n", word[flag] );
	}
	delTrie( root );
	return 0;
} 


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