字典树是哈希树的一种,通常用于字符串匹配,由于思想和实现都很简单,所以我就不再介绍了,自己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];}elsep = 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" );elseprintf( "%s\n", word[flag] );}delTrie( root );return 0;
}