hiho1014: Trie树
2015-10-10 21:08
162 查看
Trie树,并不难理解,但带数组的结构体比较神奇也是字典树的精髓,感觉好厉害!
看了大神的代码,好赞!!
我是大神的trie树~
然而我的改了n多遍第一个样例总是2,不明白,求大神指点,唉,改了一下午,忧伤……
以上是ac代码……以下是我的wa代码……心塞……
痛痛痛!!!
看了大神的代码,好赞!!
我是大神的trie树~
然而我的改了n多遍第一个样例总是2,不明白,求大神指点,唉,改了一下午,忧伤……
#include<cstdio> #include<cstdlib> #include<iostream> #include<cstring> #include<cmath> #define L 10+1 //每个单词的长度 using namespace std; struct T{ int num; T* next[26]; T(){ num=0; int i; for(i=0;i<26;i++) next[i]=NULL; } }t; void In(char str[]){ T* p=&t; for(int i=0;str[i];i++){ int a=str[i]-'a'; if(p->next[a]==NULL) p->next[a]=new T; p=p->next[a]; p->num++; } } int find(char str[]){ T* p=&t; for(int i=0;str[i];i++){ int a=str[i]-'a'; if(p->next[a]==NULL)return 0; p=p->next[a]; } return p->num; } int main(){ int n,m; char str[L]; for(scanf("%d",&n);n--;) scanf("%s",str),In(str); for(scanf("%d",&m);m--;) scanf("%s",str),printf("%d\n",find(str)); return 0; }我是ac代码
以上是ac代码……以下是我的wa代码……心塞……
#include <iostream> #include <string> #include <stdio.h> #include <stack> #include <stdlib.h> using namespace std; #define max 26 typedef struct TrieNode { bool isStr; int num=0; struct TrieNode *next[max]; //儿子分支 }Trie; void insert(Trie *root,const char *s) { if (root==NULL||*s=='\0') { return; } int i; Trie *p=root; while (*s!='\0') { if (p->next[*s-'a']==NULL) { Trie *temp=(Trie *)malloc(sizeof(Trie)); for (i=0; i<max; i++) { temp->next[i]=NULL; } temp->isStr=false; temp->num++; p->next[*s-'a']=temp; p=p->next[*s-'a']; } else { p->num++; p=p->next[*s-'a']; } s++; } p->isStr=true; //单词结束的地方标记此处可以构成一个单词 } int search(Trie *root,const char *s) { if (root==NULL||*s=='\0') { return 0; } Trie *p=root; int x=10000; while (*s!='\0') { x=p->num; //cout<<x<<endl; p=p->next[*s-'a']; //cout<<*s<<endl; if (p==NULL) { return 0; } //x=p->num; s++; } return x; } void del(Trie *root) { int i; for (i=0; i<max; i++) { if (root->next[i]!=NULL) { del(root->next[i]); } } free(root); } int main() { int i; int n,m; cin>>n; Trie *root=(Trie *)malloc(sizeof(Trie)); for (i=0; i<26; i++) { root->next[i]=NULL; } root->isStr=false; root->num=0; for (i=0; i<n; i++) { char s[101]; scanf("%s",s); //cout<<s<<endl; insert(root, s); } Trie *r=root; for (i=0; i<max; i++) { if (r->next[i]!=NULL) { cout<<i<<" "; } } cout<<endl; cout<<root->num<<endl; cin>>m; for (i=0; i<m; i++) { char s[101]; scanf("%s",s); cout<<search(root,s)<<endl; } del(root); return 0; }
痛痛痛!!!
相关文章推荐
- 《ArcGIS Runtime SDK for Android开发笔记》——问题集:.geodatabase创建,创建时内容缺失问题总结
- JS 跨域
- MySQL学习笔记
- Codeforces Round #319 (Div. 1)C. Points on Plane 分块思想
- 第一阶段考核中的JAVA简答题
- Drupal8 新建第一个模块
- opencv 应用程序无法正常启动(0xooooo7b)
- C++Primer第五版 练习11.31-32(解答)
- leetcode-reverse words in a string
- POJ 1661 Help Jimmy (DP)
- min 宏定义 避免副作用
- Validform 学习笔记---代码练习
- mybatis02 架构
- UML——类图
- FastDFS安装部署
- 编写一个C#程序,要求从键盘输入10个数存放在数组中,分别求出最大数和最小数存放在第一第二个元素里
- Android每日范例——密码输入框
- 解析JSON数据系列1:在网页上显示Json数据
- SDOI(队列)
- Struts2中配置默认Action