字典树确实是个好东西,操作也比较简单,插入,和查询是字典树的基本操作。只要语法过硬,看下字典树的插入和查询的范例,没什么难度的。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
struct tire{
int num;
tire *next[26];
tire(){
num=0;
memset(next,0,sizeof(next));
}
};
tire *root=new tire;
void insert(char *st) //插入
{
int i=0;
tire *tmp=root;
while(st[i]){
int pos=st[i]-'a';
if(tmp->next[pos]==0)
tmp->next[pos]=new tire;
tmp=tmp->next[pos];
tmp->num++;
i++;
}
}
void search(char *st) //查询
{
int i=0;
tire *tmp=root;
while(st[i]){
int goal=st[i]-'a';
if(tmp->num==1) return ;
cout<<st[i];
tmp=tmp->next[goal];
i++;
}
}
int main()
{
char st[1001][21];
int cnt=0;
while(scanf("%s",st[cnt])!=EOF){
insert(st[cnt]);
cnt++;
}
for(int i=0;i<cnt;i++){
cout<<st[i]<<" ";
search(st[i]);
cout<<endl;
}
return 0;
}