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

最新文章

  1. 项目开发(Require + E.js)
  2. pythonchallenge 解谜
  3. 用T4 Template生成代码
  4. ORA-00020: No more process state objects available故障一例
  5. simple demo how to get the list of online users
  6. js倒计时 重发 效果
  7. 【前端】:Dom
  8. IntelliJ IDEA运行慢解决方法
  9. PHP输出打印方法
  10. java的Calendar,获取月份少一月的问题及其它注意事项
  11. 【故障公告】推荐系统中转站撑爆服务器 TCP 连接引发的故障
  12. BZOJ3236[Ahoi2013]作业——莫队+树状数组/莫队+分块
  13. blfs(systemd版本)学习笔记-构建gnome桌面系统后的配置及安装的应用
  14. mysql_day03
  15. InfluxDB 1.6文档
  16. p,np,npc,np难问题,确定图灵机与非确定图灵机
  17. opacity设定图片透明度
  18. WebRTC 源码分析(五):安卓 P2P 连接过程和 DataChannel 使用
  19. CentOS 6 安装python3.6
  20. KVM入门

热门文章

  1. KeepAlived的介绍
  2. 栗染-git命令搭建简单的个人的网页
  3. taro.js &amp; dva 脚手架搭建及常见问题
  4. ADB Usage Complete / ADB 用法大全
  5. 14 C#编程中的逻辑运算
  6. Spring: (一) -- 春雨润物之 核心IOC
  7. LN : leetcode 283 Move Zeroes
  8. 60查找nanopim1plus的HDMI为720p输出的问题
  9. Android RxJava2 浅析
  10. LR接口测试---基于http协议之get/post