【ybtoj 高效进阶 2.4】【Trie树】 前缀统计

【ybtoj 高效进阶 2.4】【Trie树】 前缀统计

题目

在这里插入图片描述
在这里插入图片描述


解题思路

将这N个字符串存入Trie
用count数组求出以c结尾的字符串个数
再遍历一遍字符串T
累加以字符串T中任一字符结尾的字符串个数即为答案


代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
string x;
int t=0,n,m,count[1000010],trie[1000010][30];
inline void insert()
{
	   int len=x.size(),tot=0; 
	   for (int i=0;i<len;i++)
	   {
	   	   int c=x[i]-'a';
	   	   if (!trie[tot][c]) trie[tot][c]=++t; 
	   	   tot=trie[tot][c];
	   }
	   count[tot]++; 
}
inline int answer()
{
	   int len=x.size(),tot=0,ans=0;
	   for (int i=0;i<len;i++)
	   {
	   	   int c=x[i]-'a';
	   	   tot=trie[tot][c];   
	   	   if (!tot) //已经枚举到叶子节点了
		      return ans;
	   	   ans+=count[tot];  
	   }
	   return ans;
}
int main()
{
	scanf("%d%d",&n,&m);
	for (int i=1;i<=n;i++)
	{
		cin>>x;
		insert();  //插入
	}
	for (int i=1;i<=m;i++)
	{
		cin>>x;
		int d=answer();  //累加
		printf("%d\n",d);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值