字典树 (Trie)

P8306 【模板】字典树

#include<bits/stdc++.h>
#define cs const
#define il inline
#define ri register
#define pc(i) putchar(i)
using namespace std;
cs int N=3e6+7;
char ss[N];
int n,T,q,cnt[N],tot,t[N][65],w,mp[65];
il void read(int &as)
{
	as=0;int f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9') as=(as<<3)+(as<<1)+(ch^48),ch=getchar();as*=f;
}
void wt(int x){if(x<0) x=-x,pc('-');if(x>9) wt(x/10);pc(x%10|48);}
int ch(char x)
{
    if(x>='A'&&x<='Z') return x-'A';
    else if(x>='a'&&x<='z') return x-'a'+26;
    else return x-'0'+52;
} 
il void insert(char s[])
{
	int len=strlen(s),p=0;
	for(ri int i=0;i<len;++i)
	{
		int c=ch(s[i]);
		if(!t[p][c]) t[p][c]=++tot;
		p=t[p][c],cnt[p]++;
	}
}
il int find(char s[])
{
	int p=0,len=strlen(s);
	for(ri int i=0;i<len;++i)
	{
		char c=ch(s[i]);
		if(!t[p][c]) return 0;
		p=t[p][c];
	}
	return cnt[p];
}
signed main()
{
	read(T);
	while(T--)
	{
		read(n),read(q);
		for(ri int i=0;i<=tot;++i)
			for(int j=0;j<=99;j++) t[i][j]=0;
		for(int i=0;i<=tot;i++) cnt[i]=0; tot=0;
		for(ri int i=1;i<=n;++i) scanf("%s",ss),insert(ss);
		for(ri int i=1;i<=q;++i) scanf("%s",ss),wt(find(ss)),pc('\n');
	}
	return 0;
 } 

参考 https://www.luogu.com.cn/blog/333800/p8306-mu-ban-zi-dian-shu-ti-xie

posted @   Bertidurlah  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示