字典树
来源:互联网 发布:linux apache安装目录 编辑:程序博客网 时间:2024/06/06 05:47
#include<cstdio>#include<cstring>#include<algorithm>#define idx(x) (x-'a')using namespace std;int n,m; //输入字符串数 查询次数 int ant; //记录当前在哪一层 struct Node{ int v; //当前有多少个字符串共用这个数组 Node *next[26]; //指针数组指向下一层 void init() //清空本层 { v=0; for(int i = 1;i <= 26; i++) { next[i] = NULL; } }}trie[100000];void insert(char *str){ Node *p = &trie[0]; //现在执行到的节点 int len = strlen(str); for(int i = 0; i < len; i++) { if(p -> next[idx(str[i])] == NULL) { p -> next[idx(str[i])] = &trie[ant]; //如果节点为空则赋值此节点 ant++; trie[ant].init(); //初始化下一层 trie[ant-1].v=1; p = &trie[ant-1]; } else { p->v++; p = p -> next[idx(str[i])]; } } }int Querylen(char *str){ Node p = trie[0]; int lenth = 0; int l = strlen(str); for(int i = 0; i < l ; i++) { if(p.next[idx(str[i])] == NULL) //到此结点无公共前缀 结束循环 break; else { lenth++; p = *p.next[idx(str[i])]; //向下一层出发 } }return lenth; }int main(){ char str[20]; scanf("%d %d",&n,&m); trie[ant].init(); for(int i = 1; i <= n; i++) { scanf("%s",str); insert(str); } for(int i = 1;i <= m; i++) { scanf("%s",str); printf("%d\n",Querylen(str)); }return 0; }
示例:
阅读全文
0 0
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树。。
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- codeforces840C On the Bench -- DP
- python3.4 获取cookie后继续访问其他页面
- java提高篇(五)-----抽象类与接口
- 输出字典的键(key)
- 给你一个字符串,里面只包含"(",")","[","]"四种符号,请问你需要至少添加多少个括号才能使这些括号匹配起来。
- 字典树
- vittualbox5.1 自动挂载共享文件夹
- Maven的核心概念
- ajax
- android 小功能之----修改状态栏蓝色
- nova代码中修改虚机xml文件
- 图片轮播并加载网络数据
- 如何看代码
- 51nod 1412-AVL树的种类(DP)