Trie树 hihocoder 1014
2024-09-30 22:15:02
Trie树 hihocoder 1014
字典树的基本应用
#include<queue>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define ll long long
#define inf 1000000000
#define mod 1000000007
using namespace std;
int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
const int sigma=26;
typedef struct node
{
int id;
struct node *next[sigma];
}Trie;
const int N=100000+10;
void insert(Trie *root,char *str)
{
Trie *p=root;
int n=strlen(str);
for(int i=0;i<n;i++)
{
int c=str[i]-'a';
if(p->next[c]==NULL)
{
Trie *tmp=new Trie;
for(int j=0;j<sigma;j++) tmp->next[j]=NULL;
tmp->id=0;
p->next[c]=tmp;
}
p->id++;
p=p->next[c];
}
p->id++;
}
int search(Trie *root,char *str)
{
Trie *p=root;
int n=strlen(str);
for(int i=0;i<n;i++)
{
int c=str[i]-'a';
if(p->next[c]==NULL) return 0;
p=p->next[c];
}
return p->id;
}
void Del(Trie *root)
{
for(int i=0;i<sigma;i++) if(root->next[i]!=NULL) Del(root->next[i]);
delete root;
}
char str[N];
int main()
{
int cnt=0;
Trie *root=new Trie;
for(int i=0;i<sigma;i++) root->next[i]=NULL;
root->id=false;
int n;
n=read();
for(int i=1;i<=n;i++)
{
scanf("%s",str);
insert(root,str);
}
int m=read(),idx;
while(m--)
{
scanf("%s",str);
idx=search(root,str);
printf("%d\n",idx);
}
Del(root);
return 0;
}
最新文章
- 项目开发(Require + E.js)
- pythonchallenge 解谜
- 用T4 Template生成代码
- ORA-00020: No more process state objects available故障一例
- simple demo how to get the list of online users
- js倒计时 重发 效果
- 【前端】:Dom
- IntelliJ IDEA运行慢解决方法
- PHP输出打印方法
- java的Calendar,获取月份少一月的问题及其它注意事项
- 【故障公告】推荐系统中转站撑爆服务器 TCP 连接引发的故障
- BZOJ3236[Ahoi2013]作业——莫队+树状数组/莫队+分块
- blfs(systemd版本)学习笔记-构建gnome桌面系统后的配置及安装的应用
- mysql_day03
- InfluxDB 1.6文档
- p,np,npc,np难问题,确定图灵机与非确定图灵机
- opacity设定图片透明度
- WebRTC 源码分析(五):安卓 P2P 连接过程和 DataChannel 使用
- CentOS 6 安装python3.6
- KVM入门