HDOJ 1251 统计难题(j简单的字典树trie的应用)

本文介绍了一种字典树(Trie)的数据结构实现方式,并提供了完整的C++代码示例。通过该实现可以高效地进行字符串查找、插入等操作。文章详细解释了如何构建字典树节点、如何插入新单词以及如何查找特定单词出现的次数。

整理一下自己的字典树模板。

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 15;
typedef struct Trie_Node
{
        struct Trie_Node *next[26];
	int val;
}Trie;
void insert(Trie *root, char *s)
{
	Trie *p = root;
	int i = 0;
	while(s[i] != '\0')
	{
		if(p->next[s[i]-'a'] == NULL)
		{
			Trie *temp = new Trie;
			for(int j=0;j<26;j++)
				temp->next[j] = NULL;
			temp->val = 0;
			p->next[s[i]-'a'] = temp;
		}
		p = p->next[s[i]-'a'];
		p->val++;
		i++;
	}
}
int Find(Trie *root, char *s)
{
	Trie *p = root;
	int i = 0;
	while(s[i] != '\0')
	{
		if(p->next[s[i]-'a'] == NULL)
			return 0;
		p = p->next[s[i]-'a'];
		i++;
	}
	return p->val;
}
int main()
{
	char s[20];
	Trie *root = new Trie;
	for(int i=0;i<26;i++)
		root->next[i] = NULL;
	root->val = 0;
	while(gets(s) && strlen(s)) insert(root, s);
	while(gets(s))
	{
		printf("%d\n", Find(root,s));
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值