HDU 1251 [字典树] --by二汪

题目链接

/*

-------------字典树----------
利用主字符串组来构造树
可以查询以模式串为前缀的主字符串的个数 
只能查前缀!!!


*/
#include<iostream>
#include<string>
#include<string.h>
#include<vector>
#include<cstdio>
#include<algorithm>
#include<map>
#include<set>
#include<cmath>
using namespace std;
#define ll long long
#define pi acos(-1)
const int maxn = 1e6+5;

int trie[maxn][26];   //字典树
int book[maxn];   //标记每个节点出现几次 
int id;   //当前字典树中有几个节点


inline void insert(char *s)  //将字符串s插入字典树中 
{
	int len = strlen(s);
	int p = 0;   //从0节点开始 
	
	for(int i=0;i<len;++i)
	{
		int c = s[i] - 'a';
		if(!trie[p][c])   //没有边,就加边
			trie[p][c] = ++id;
		
		p = trie[p][c];
		++book[p]; 
	}
} 

inline search(char *s)   //查找模式串s 
{
	int len = strlen(s);
	int p = 0;	//从0节点开始查找 
	
	for(int i=0;i<len;++i)
	{
		int c = s[i] - 'a';
		if(!trie[p][c]) 
			return 0;
		p = trie[p][c];
	}
	
	return book[p];  //返回模式串s在字典树中出现的次数 
}

signed main()
{
	char ss[505];
	while(gets(ss))
	{
		if(ss[0]=='\0') break;
		insert(ss);
	}
	while(~scanf("%s",ss))
	{
		printf("%d\n",search(ss));
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值