Trie

本文介绍了一段使用C++实现Trie树的数据结构代码。该代码通过Trie树进行字符串插入与查询操作,适用于文本搜索等场景。文章详细解释了Trie树的构建过程及其在实际应用中的效能。

今晚花了点时间研究了这谜一般的代码。。。。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
const int charset=26,base='a',max_node=100000;
//charset 为字符集大小
//base 为字符集ASCII最小字符
//max_node为最大点数
struct Trie{
	int tot,root,child[max_node][charset];
	bool flag[max_node];
	Trie(){
		memset(child[1],0,sizeof(child[1]));
		flag[1]=false;
		root=tot=1;
	}
	void insert(const char *str){
		int *cur=&root;
		for(const char *p=str;*p;++p){
			cur=&child[*cur][*p-base];
			if(*cur==0){
				*cur=++tot;
				memset(child[tot],0,sizeof(child[tot]));
				flag[tot]=false;
			}
		}
		flag[*cur]=true;
	}
	bool query(const char *str){
		int *cur=&root;
		for(const char *p=str;*p && *cur;++p)cur=&child[*cur][*p-base];
		return (*cur && flag[*cur]); 
	} 
}trie;
int main(){
	int i,j,k,m,n;
	char s[2000];
	cin>>n;
	while(n--){
		cin>>s;
		trie.insert(s);
	}
	cin>>n;
	while(n--){
		cin>>s;
		cout<<trie.query(s)<<endl;
	}
	return 0;
}


转载于:https://www.cnblogs.com/brodrinkwater/p/7528001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值