HDU2846——Repository
来源:互联网 发布:网络市场调研方法 编辑:程序博客网 时间:2024/06/04 00:40
写完前面那几篇字典树的总结,感觉自己对字典树模板熟练了许多,然后没参考网上的代码,自己花了几分钟a了这一题,感觉真好。
这题先得把每个字符串分串,每一个子串都插入。
然后还要在结构体内加个index,来保证同一个单词相同的子串不会被重复计数。
#include <stdio.h>#include <ctype.h>#include <string.h>#include <stdlib.h>#include <limits.h>#include <math.h>#include <algorithm>using namespace std;const int MAX=26;typedef struct TrieNode{int index; int nCount; // 该节点前缀 出现的次数 struct TrieNode *next[MAX]; //该节点的后续节点} TrieNode;TrieNode Memory[1000000]; //先分配好内存。 malloc 较为费时int allocp = 0;//初始化一个节点。nCount计数为1, next都为nullTrieNode * createTrieNode(int j){ TrieNode * tmp = &Memory[allocp++];tmp->index=j; tmp->nCount = 1; for (int i = 0; i < MAX; i++) tmp->next[i] = NULL; return tmp;}void insertTrie(TrieNode * pRoot, char * str,int j){ TrieNode * tmp = pRoot; int i = 0, k; //一个一个的插入字符 while (str[i]) { k = str[i] - 'a'; //当前字符 应该插入的位置 if (tmp->next[k]) {if(tmp->next[k]->index==j);else{tmp->next[k]->nCount++;tmp->next[k]->index=j;} } else { tmp->next[k] = createTrieNode(j); } tmp = tmp->next[k]; i++; //移到下一个字符 }}int searchTrie(TrieNode * root, char * str){ if (root == NULL) return 0; TrieNode * tmp = root; int i = 0, k; while (str[i]) { k = str[i] - 'a'; if (tmp->next[k]) { tmp = tmp->next[k]; } else return 0; i++; } return tmp->nCount; //返回最后的那个字符 所在节点的 nCount}int main(void){ char s[30];char temp[30];int T,length;int i;int j;TrieNode *Root = createTrieNode(0);scanf("%d",&T);for(j=1;j<=T;j++){scanf("%s",s);length=strlen(s);for(i=0;i<length;i++){strcpy(temp,s+i);//printf("%s\n",temp);insertTrie(Root,temp,j);}}scanf("%d",&T);for(i=1;i<=T;i++){scanf("%s",temp);printf("%d\n",searchTrie(Root,temp));} return 0;}
0 0
- HDU2846——Repository
- hdu2846 Repository
- HDU2846-Repository
- HDU2846-Repository
- HDU2846 Repository, Trie树
- hdu2846 Repository (字典树)
- hdu2846 Repository 字典树
- HDU2846 Repository 字典树
- hdu2846 Repository (字典树)
- hdu2846 Repository -字典树
- hdu2846 Repository(字典树)
- hdu2846 Repository(Tire树)
- hdu2846 Repository 字典树(好题)
- hdu2846
- HDU2846
- hdu2846
- hdu2846
- hdu2846(动态字典树||静态字典树 模板)Repository
- ZOJ_2104_Let the Balloon Rise
- 关于IE8不支持Object.keys()的处理
- 电信141p122第6题
- 关于clean code 的感想
- 物以类聚 – 对象和类
- HDU2846——Repository
- vs 安装不同office引起编译不通过
- Android NDK c创建java对象
- 腾讯校园招聘 涟漪动画的实现
- [G+smo]openNurbs相关的CAD文件格式转换
- 9. CATransform3D 特效详解
- 二分匹配_HDU
- Spring对Cache的支持
- Android环境搭建遇到的问题