字典树模板
来源:互联网 发布:易名中国域名管理系统 编辑:程序博客网 时间:2024/06/04 05:49
动态树
code
#include <iostream>using namespace std;const int MAXM = 30,KIND = 26;int m;struct node{ char* s; int prefix; bool isword; node* next[KIND]; node() { s = NULL; prefix = 0; isword = false; memset(next,0,sizeof(next)); }}*root;//根void insert(node *root,char *s)//插入{ node *p = root; for (int i = 0;s[i];i++) { int x = s[i] - 'a'; p->s = s+i; if (p->next[x] == NULL) p->next[x] = new node; p = p->next[x]; p->prefix++; } p->isword = true;}bool del(node *root,char *s)//删除{ node *p = root; for (int i = 0;s[i];i++) { int x = s[i] - 'a'; if (p->next[x] == NULL) return false; p = p->next[x]; } if (p->isword) p->isword = false; else return false; return true;}bool search(node *root,char* s)//查找s这个字符串,是否出现过{ node* p = root; for (int i = 0;s[i];i++) { int x = s[i]-'a'; if (p->next[x] == NULL) return false; p = p->next[x]; } return p->isword;}int count(node *root,char *s)//统计以s作为前缀的字符串的个数{ node *p = root; for (int i = 0;s[i];i++) { int x = s[i] - 'a'; if (p->next[x] == NULL) return 0; p = p->next[x]; } return p->prefix;}int main(){ m = 0; root = new node; char s[MAXM]; while (gets(s)) { if (strcmp(s,"") == 0) break; insert(root,s); } while (gets(s)) printf("%d\n",count(root,s));}
///静态trie
code
#include <iostream>using namespace std;const int MAXN = 100010,MAXM = 30,KIND = 26;int m;struct node{ char* s; int prefix; bool isword; node* next[KIND]; void init() { s = NULL; prefix = 0; isword = false; memset(next,0,sizeof(next)); }}a[MAXN*MAXM],*root;//根void insert(node *root,char *s){ node *p = root; for (int i = 0;s[i];i++) { int x = s[i] - 'a'; p->s = s+i; if (p->next[x] == NULL) { a[m].init(); p->next[x] = &a[m++]; } p = p->next[x]; p->prefix++; } p->isword = true;}bool del(node *root,char *s){ node *p = root; for (int i = 0;s[i];i++) { int x = s[i] - 'a'; if (p->next[x] == NULL) return false; p = p->next[x]; } if (p->isword) p->isword = false; else return false; return true;}bool search(node *root,char* s){ node* p = root; for (int i = 0;s[i];i++) { int x = s[i]-'a'; if (p->next[x] == NULL) return false; p = p->next[x]; } return p->isword;}int count(node *root,char *s){ node *p = root; for (int i = 0;s[i];i++) { int x = s[i] - 'a'; if (p->next[x] == NULL) return 0; p = p->next[x]; } return p->prefix;}int main(){ m = 0; a[m].init(); root = &a[m++]; char s[MAXM]; while (gets(s)) { if (strcmp(s,"") == 0) break; insert(root,s); } while (gets(s)) printf("%d\n",count(root,s));}
阅读全文
1 0
- 字典树 模板
- 字典树【模板】
- 字典树模板
- 字典树模板
- 字典树模板
- 经典字典树模板
- hdu1247 字典树模板
- 字典树模板
- 字典树模板
- 字典树模板
- 字典树模板
- 字典树 模板
- 1251 字典树 模板
- 数据结构 字典树模板
- 字典树模板
- 字典树(trie)模板
- 字典树 模板+讲解
- 字典树模板
- #ifndef #define #endif
- 二叉树的翻转 Python
- 每日一题(18)—— 指定地址存入数据
- 个人对背包问题的二进制优化问题的理解
- nodeJS之流stream
- 字典树模板
- centos下安装docker
- 图论题
- php连接数据库
- 每天一点MySQL-分组数据
- 原码、反码、补码
- Hibernate(一)(五大核心接口及sessionFactory的两种创建方式)
- Elasticsearch
- jdk中的红黑树实现