POJ2001 字典树

写法一:

#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[n]);
		for(i=0;i<k;i++){
			if(p->next[s[n][i]-'a']==NULL){
				q=new node;
				q->count=1;
				for(j=0;j<26;j++)q->next[j]=NULL;
				p->next[s[n][i]-'a']=q;
				p=q;
			}else{
				p=p->next[s[n][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[n]);
	
	for(i=1;i<=n;i++){
		printf("%s ",s[i]);
		search(s[i]);
		printf("\n");		
	}		
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值