HDU 1251 统计难题(字典树模板题)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

HDU 1251 统计难题

题意

        统计出以某个单词作为前缀的单词的数量,单词本身也属于单词的前缀。如字符串abc的前缀为a,ab,abc。

思路

        字典树模板题目,在往字典树内插入一个单词时,每个经过的结点的sum值都加1,最后通过前缀单词到达的结点的sum值输出答案。

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn=2e6+10;

int tree[maxn][30];//tree[i][j]表示节点i的第j个儿子的节点编号
int sum[maxn];//记录节点访问次数
int tot;//总节点数
char s[maxn];

void insert_(char *str)
{
	int len=strlen(str);
	int root=0;
	for(int i=0;i<len;i++){
		int id=str[i]-'a';
		if(!tree[root][id]) tree[root][id]=++tot;
		sum[tree[root][id]]++;
		root=tree[root][id];
	}
}

int find_(char *str)
{
	int len=strlen(str);
	int root=0;
	for(int i=0;i<len;i++){
		int id=str[i]-'a';
		if(!tree[root][id]) return 0;
		root=tree[root][id];
	}
	return sum[root];//返回当前字符串结尾节点的访问次数,也就是作为前缀的出现次数
}

int main()
{
	while(gets(s)){
		if(s[0]=='\0') break;
		insert_(s);
	}
	while(~scanf("%s",s)){
		printf("%d\n",find_(s));
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值