当前位置:网站首页>字典树模板
字典树模板
2022-04-22 05:35:00 【lxt1101】
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample
| Inputcopy | Outputcopy |
|---|---|
banana band bee absolute acm ba b band abc |
2 3 1 0 |
#include<iostream>
#include<math.h>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define ll long long
const int maxn = 1e6 + 10;
int tree[maxn][30];
ll sum[maxn];
bool flag[maxn];
int tot;
void build_tree(char* s) {
int root = 0;
int id;
int len = strlen(s);
for (int i = 0; i < len; i++) {
id = s[i] - 'a';
if (!tree[root][id])tree[root][id] = ++tot;
sum[tree[root][id]]++;//每一次有单词到这就加一,就可以知道后面有多少个单词了
root = tree[root][id];
}
flag[root] = true;
}
ll find(char* s) {
int root = 0;
int id;
ll res = 0;
int len = strlen(s);
for (int i = 0; i < len; i++) {
id = s[i] - 'a';
if (!tree[root][id])return 0;
root = tree[root][id];
}
return sum[root];
}
char s[maxn];
int main() {
while (gets(s)) {
if (s[0] == '\0')break;
build_tree(s);
}
while (cin >> s) {
cout << find(s) << endl;
}
return 0;
}
版权声明
本文为[lxt1101]所创,转载请带上原文链接,感谢
https://blog.csdn.net/lxt1101/article/details/124085706
边栏推荐
- Goodbye 20202021 I'm coming
- Force buckle - 322 Change
- Single machine deployment redis master-slave and sentinel mode (one master, two slave and three sentinels)
- 机器学习——用鸢尾花数据集画P-R曲线和ROC曲线
- 常见的状态码
- 数字三角形(动态规划dp)
- Strong connected component of "tarjan" undirected graph
- fastjson判断JSON字符串是Object还是List<Object>
- mysql非常用命令
- 再见2020,2021我来了
猜你喜欢
随机推荐
数字三角形(动态规划dp)
数据已删除,又重新出现的问题排查
AcWing 836. 合并集合(并查集)
Five important properties of binary tree
判断链表是否有环
My common development software
代码整洁之道学习
数位dp(模板)
Array division (backpack)
元注解(注解的注解)
折现分割平面
MySQL 第6章 Navicat 的安装与使用
Simulate the infectious disease model with MATLAB (only do matlab simulation learning and practice, not actual situation and application)
C語言練習(2)——鏈錶實現多項式加法
Domain based approach - score prediction
seata分布式事务项目中无法传递xid的问题
MySQL偶尔的卡顿
List stream: usage instance of reduce
strlen的三种实现方法你知道吗?
C language practice (2) -- polynomial addition with linked list






