统计难题 HDU - 1251(字典树,getline的使用)

本文介绍了一种使用字典树(Trie)的数据结构来高效地进行字符串前缀搜索的方法。通过在每个节点设置计数器,可以统计特定前缀出现的次数。文章提供了完整的C++代码实现,包括插入和搜索操作。

本题用字典树即可,在每个节点上设置一个计数变量cnt,用于统计从根节点到本节点的前缀的数量。

#include <iostream>
#include <string>
#include <string.h>

using namespace std;

typedef struct Node
{
	int cnt;
	Node *child[26];
	Node()
	{
		cnt = 1;
		memset(child, 0, sizeof(child));
	}
};

Node *root = new Node; 

void Insert(string str)
{
	int len = str.length();
	Node *p = root;
	for(int i = 0; i < len; i++)
	{
		int id = str[i] - 'a';
		if(p->child[id] == 0)
			p->child[id] = new Node;
		else
			p->child[id]->cnt++;
		p = p->child[id];
	}
}

void Search(string str)
{
	int len = str.length();
	Node *p = root;
	for(int i = 0; i < len; i++)
	{
		int id = str[i] - 'a';
		if(p->child[id] != 0)
			p = p->child[id];
		else
		{
			cout << 0 << endl;
			return;
		}
	}
	cout << p->cnt << endl;
}

int main()
{
	string str;
	//getline()会把回车符也读入进str中,而且长度为0 
	while(getline(cin, str) && str.length() != 0)
		Insert(str);
	
	while(cin>> str)
		Search(str);
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值