trie树常用于搜索提示。如当输入一个网址,可以自动搜索出可能的选择。当没有完全匹配的搜索结果,可以返回前缀最相似的可能。
/*
File Name :10815.cpp
Author : erlingyier
Created Time: 2014年08月26日 星期二 14时27分46秒
*/
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
//Trie
typedef struct node1
{
bool flag;
node1 *next[26];
}tnode;
tnode dict[50000];
class Tire
{
tnode* root;
int size;
char save[201];
public:
Tire() {size = 0;root = newnode();}
int ID( char ch ) {
if ( ch <= 'Z' ) return ch-'A';
else return ch-'a';
}
//构造新节点
tnode* newnode() {
for ( int i = 0 ; i < 26 ; ++ i )
dict[size].next[i] = NULL;
dict[size].flag = false;
return &dict[size ++];
}
//单词插入
void insert( char* word, int len ) {
tnode *now = root;
for ( int i = 0 ; i < len ; ++ i ) {
if ( !now->next[ ID(word[i]) ] )
now->next[ ID(word[i]) ] = newnode();
now = now->next[ ID(word[i]) ];
}now->flag = true;
}
//利用dfs遍历输出
void output( tnode* r, int d ) {
if ( r->flag ) {
save[d] = 0;puts(save);
}
for ( int i = 0 ; i < 26 ; ++ i )
if ( r->next[i] ) {
save[d] = i+'a';
output( r->next[i], d+1 );
}
}
void output(){ output(root,0); }
};
//Tire end
int main()
{
char buf[201],sav[201];
Tire tire;
while ( gets(buf) ) {
int len = strlen(buf);
int cou = 0;
for ( int i = 0 ; i <= len ; ++ i )
if ( (buf[i] >= 'a' && buf[i] <= 'z') ||
(buf[i] >= 'A' && buf[i] <= 'Z') )
sav[cou ++] = buf[i];
else if ( cou ) {
sav[cou] = 0;
tire.insert( sav, cou );
cou = 0;
}
}
tire.output();
return 0;
}