您的位置:首页 > 其它

POJ2001 字典树

2015-08-04 01:16 405 查看
写法一:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node{
int count;
struct node *next[26];
};
struct node *root,*p,*q;
char s[1010][25];
int main(){
int i,j,k,m,n=0;
root=new node;
root->count=0;
for(i=0;i<26;i++)root->next[i]=NULL;

while(scanf("%s",&s[++n])!=EOF){
p=root;
k=strlen(s
);
for(i=0;i<k;i++){
if(p->next[s
[i]-'a']==NULL){
q=new node;
q->count=1;
for(j=0;j<26;j++)q->next[j]=NULL;
p->next[s
[i]-'a']=q;
p=q;
}else{
p=p->next[s
[i]-'a'];
p->count++;
}
}
}

for(i=1;i<=n;i++){
printf("%s ",s[i]);
p=root;
k=strlen(s[i]);
for(j=0;j<k;j++){
p=p->next[s[i][j]-'a'];
printf("%c",s[i][j]);
if(p->count==1)break;
}
printf("\n");
}
return 0;
}


写法二:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node{
int count;
struct node *next[26];
node(){
count=0;
memset(next,0,sizeof(next));
}
};
struct node *root,*p,*q;
char s[1010][25];
void insert(char *st){
int i,j,k;
p=root;
k=strlen(st);
for(i=0;i<k;i++){
if(p->next[st[i]-'a']==NULL){
q=new node;
p->next[st[i]-'a']=q;
}
p=p->next[st[i]-'a'];
p->count++;
}
}
void search(char *st){
int i,j,k;
p=root;
k=strlen(st);
for(i=0;i<k;i++){
p=p->next[st[i]-'a'];
printf("%c",st[i]);
if(p->count==1)break;
}
}
int main(){
int i,j,k,m,n=0;
root=new node;

while(scanf("%s",&s[++n])!=EOF)
insert(s
);

for(i=1;i<=n;i++){
printf("%s ",s[i]);
search(s[i]);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: