trie树—数据结构
来源:互联网 发布:ubuntu如何安装deb软件 编辑:程序博客网 时间:2024/04/28 21:03
首先贴出来引用的两个链接:
http://zh.wikipedia.org/wiki/Trie
http://blog.csdn.net/hackbuteer1/article/details/7964147
trie树又叫字典树,一个典型应用就是搜索提示。本次代码就是这个例子。:)
先贴一个trie树的图
代码如下:
#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<queue>using namespace std;typedef struct _trieNode{ int count; //统计单词出现的次数 struct _trieNode* next[26] ; bool exist; //是否出现过该单词}trieNode;int ans = 0;trieNode* createTrieNode(){ trieNode* node = (trieNode*)malloc(sizeof(trieNode)); node->count = 0; node->exist = false; memset(node->next,NULL,sizeof(node->next));//0 return node;}void insertTrie(trieNode* root,char w[]){ trieNode* u = root; for(int i = 0; w[i] != '\0';i++) { int n = w[i] - 'a'; if(u->next[n] == NULL) { u->next[n] = createTrieNode(); } u = u->next[n]; } u->count++; u->exist = true;}trieNode* searchTrie(trieNode*root,char w[]){ trieNode* u = root; for(int i = 0; w[i] != '\0'; i++) { u = u->next[w[i] - 'a']; } return u;}void DFS(trieNode*r,char w[],int pos){ trieNode* u = r; if(u->exist) { printf("%s\n",w); } for(int i = 0; i < 26; i++) { if(u->next[i] != NULL) { w[pos++] = 'a' + i; w[pos] = '\0'; DFS(u->next[i],w,pos); pos--; w[pos] = '\0'; } } return ;}int main(){ FILE *fp = fopen("in.txt","r"); char w[15]; char t[15]; trieNode* root = createTrieNode(); while(fscanf(fp,"%s",w) != EOF) { //printf("%s\n",w); insertTrie(root,w); } cout<<"请输入你要查询的词:"<<endl; while(scanf("%s",t) != EOF) { DFS(searchTrie(root,t),t,strlen(t)); cout<<"请输入你要查询的词:"<<endl; } system("pause"); return 0;}
0 0
- trie树—数据结构
- 数据结构系列——Trie树
- 数据结构:TRIE树
- 数据结构:TRIE树
- 数据结构之Trie树
- 数据结构之trie树
- 数据结构之【trie树】
- 数据结构之Trie树
- 数据结构:TRIE树
- 数据结构:TRIE树
- 数据结构之Trie树
- 数据结构之Trie树
- 数据结构之Trie树
- 数据结构之Trie树
- 数据结构-Trie树
- 数据结构之trie树
- 【数据结构】Trie树
- 数据结构之Trie树
- Windows下配置Arduino的Netbeans开发环境
- C# 连接数据库 SQLSever
- 多线程和同步有几种实现方法
- 【SQLite】SQLite的简单使用
- Java泛型-类型擦除
- trie树—数据结构
- Sql Server 2008/2005 数据库还原出现 3154错误
- Android MemoryFile 源码分析以及使用
- #!/bin/bash
- HDU 1043 八数码问题 A*搜索
- 【CareerCup】Trees and Graphs—Q4.3
- C# Socket通讯实例
- INT 13H - Wikipedia, the free encyclopedia
- java代码面试常见的算法-mark