【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;
}

猜你喜欢

转载自blog.csdn.net/qq_45621109/article/details/115024852
今日推荐