hdu 1251 统计难题(字典树)

本文介绍了一种利用字典树进行高效模式匹配的方法。通过构建字典树并统计节点覆盖情况,可以快速查找字符串前缀对应的单词数量。文中提供了完整的C++实现代码。

题目链接:hdu 1251


解法:构造一个字典树,根据给出模式串统计字典树上的结点分别被多少个单词覆盖到,统计到的某结点的ch值便是以该结点结尾的字符串为前缀的单词个数。

代码如下:

#include <cstdio>
#include <cstring>

struct trie
{
	trie *next[26]; // 假设只有26个小写字母
	int ch;         // 统计有多少个单词覆盖到当前结点
	trie() {        // 用于初始化的构造函数
		memset(next, 0, sizeof(next));
		ch = 1;
	}
} *root;

void insert(char *s)
{
	trie *p = root;
	while(*s) {
		int index = *s - 'a';
		if(p->next[index]) p->next[index]->ch++;
		else p->next[index] = new trie;
		p = p->next[index];
		s++;
	}
}

int search(char *s)
{
    trie *p = root;
	while(*s) {
		int index = *s - 'a';
		if(!p->next[index]) return 0;
		p = p->next[index];
		s++;
	}
	return p->ch;
}

int main()
{
    root = new trie;
    char s[15];
    while(gets(s), s[0] != '\0') insert(s);
    while(gets(s)) printf("%d\n", search(s));
    return 0;
}




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值