字典树

个人觉得这个模板比较好

http://www.tuicool.com/articles/6Fv2Ej

模仿这个模板我写的poj上的2001

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
struct node {
int num;
node *a[27];
    node () {
int i;
num=0;
for(i=0;i<26;i++)
a[i]=NULL;
}
}*root;
char str[1100][30];
int k;
void insert(node * root,int len) {
root->num++;
struct node *q;
int i;
for(i=0;i<=len;i++) {
if(root->a[str[k][i]-'a']!=NULL) {
   root=root->a[str[k][i]-'a'];
root->num++;
}
else {
q=new node ();
q->num++;
root->a[str[k][i]-'a']=q;
root=q;
}
}
return ;
}
void find(int len,int m,node *root) {
      int i;  
 for(i=0;i<=len;i++) {
 root=root->a[str[m][i]-'a'];
 if(root->num==1) {
printf("%c",str[m][i]);
return ;
 }
 else 
           printf("%c",str[m][i]);
 }
 return ;
}
int main(){
int i,len;
    root=new node ();
k=0;
while(scanf("%s",str[++k])!=EOF) {
len=strlen(str[k])-1;
insert(root,len);
}
k--;
for(i=1;i<=k;i++) {
printf("%s ",str[i]);
find(strlen(str[i])-1,i,root);
if(i!=k)
printf("\n");
}
return 0;
}

posted @ 2013-11-17 16:18  HYDhyd  阅读(151)  评论(0编辑  收藏  举报