hihocoder 1014 Trie树 trie

传送门:hihocoder 1014

        给出n个字符串,再给m次询问,每次给出一个字符串,问给定的n个字符串中,以该字符串为开头的字符串有多少个。


        就像题目名字一样,标标准准的trie树,在建树的过程中统计每个点被访问了多少次即可

/******************************************************
 * File Name:   1014.cpp
 * Author:      kojimai
 * Create Time: 2014年11月08日 星期六 14时14分52秒
******************************************************/

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
#define FFF 100005
struct node
{
	int cnt;
	node *next[26];
};
node* newnode()
{
	node *p = (node *)malloc(sizeof(node));
	for(int i = 0;i < 26;i++)
	{
		p->next[i] = NULL;
	}
	p->cnt = 0;
	return p;
}
void build(char *s,node *root)
{
	node *p = root;
	for(int i = 0;s[i] != '\0';i++)
	{
		int t = s[i] - 'a';
		if(p -> next[t] == NULL)
		{
			node *q = newnode();
			p -> next[t] = q;
		}
		p = p -> next[t];
		p -> cnt++;
	}
	return;
}
int solve(char *s,node *root)
{
	node *p = root;
	for(int i = 0;s[i] != '\0';i++)
	{
		int t = s[i] - 'a';
		if(p -> next[t] == NULL)
			return 0;
		else
			p = p -> next[t];
	}
	return p->cnt;
}
int main()
{
	int n,m;
	char s[23];
	scanf("%d",&n);
	node* root = newnode();
	for(int i = 0;i < n;i++)
	{
		scanf("%s",s);
		build(s,root);
	}
	scanf("%d",&m);
	for(int i = 0;i < n;i++)
	{
		scanf("%s",s);
		cout<<solve(s,root)<<endl;
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值