poj-2001字典树

12 篇文章 0 订阅

题目连接

字典树确实是个好东西,操作也比较简单,插入,和查询是字典树的基本操作。只要语法过硬,看下字典树的插入和查询的范例,没什么难度的。

代码:

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值