POJ 2001 Shortest Prefixes ( 字典树 )
来源:互联网 发布:阿里云国际200m无限 编辑:程序博客网 时间:2024/04/25 16:22
题意:给出n个单词(1<=n<=1000),求出每个单词的非公共前缀,如果没有,则输出自己。
分析:字典树的基础应用。
Trie树(字典树),又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。
它有3个基本特性:
1)根节点不包含字符,除根节点外每一个节点都只包含一个字符。
2)从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
3)每个节点的所有子节点包含的字符都不相同。
//564K16MS#include <cstdio>#include <iostream>#include <cstring>#define DEBUG puts("Hello world!") ;#define N 30using namespace std ;struct TreeNode{ int count ; // 记录用到这个节点的单词数量,如果count = 1,则证明其为这个单词唯一的节点 TreeNode *next[N] ; TreeNode( ) { count = 0 ; memset ( next , 0 , sizeof ( next ) ) ; }};TreeNode *root ;voidInsert ( char * str ){ TreeNode * temp ; temp = root ; int i ; i = 0 ; //DEBUG while ( str[i] ) { int index ; index = str[i] - 'a' ; if ( NULL == temp->next[index] ) { temp->next[index] = new TreeNode ; } temp = temp->next[index] ; temp->count ++ ; i ++ ; }}voidSearch ( char *str ){ TreeNode *temp ; temp = root ; int i ; i = 0 ; while ( str[i] ) { int index ; index = str[i] - 'a' ; if ( 1 == temp->count ) { break ; } printf ("%c" , str[i] ) ; temp = temp->next[index] ; i ++ ; }}intmain ( ){ root = new TreeNode ; char str[1005][22] ; int index ; index = 0 ; while ( EOF != scanf ("%s" , str[index] ) ) { Insert ( str[index] ) ; index ++ ; } int len ; len = index ; for ( int i = 0 ; i < len ; i ++ ) { printf ("%s " , str[i] ) ; Search ( str[i] ) ; printf ("\n") ; } return 0 ;}
- POJ 2001:Shortest Prefixes(字典树)
- poj 2001 Shortest Prefixes(字典树)
- poj 2001 -- Shortest Prefixes ( 字典树 )
- POJ 2001 Shortest Prefixes ( 字典树 )
- POJ 2001 Shortest Prefixes 字典树Trie
- POJ 2001 Shortest Prefixes(字典树Trie)
- poj 2001 Shortest Prefixes(字典树)
- [字典树] poj 2001 Shortest Prefixes
- POJ 2001 Shortest Prefixes 字典树
- POJ 2001-Shortest Prefixes(字典树)
- POJ 2001 Shortest Prefixes(字典树)
- POJ 2001 Shortest Prefixes(字典树)
- POJ【2001】Shortest Prefixes----字典树
- POJ-2001--Shortest Prefixes (字典树)
- poj 2001 Shortest Prefixes 字典树
- poj 2001 Shortest Prefixes(字典树)
- poj 2001 Shortest Prefixes(字典树)
- POJ - 2001 - Shortest Prefixes (字典树!!)
- leetcode: Search for a Range
- 编程之美2.21 只考加法的面试题
- [Android] ADT关联源码与API文档
- Mahout协同过滤算法源码分析(2)--splitDataset 和parallelALS
- C++关于typeinfo
- POJ 2001 Shortest Prefixes ( 字典树 )
- java基础入门----- 高级for循环1
- java基础入门----- 高级for循环2
- 推荐链接2
- virtualbox虚拟机错误
- java基础入门-----可变参数
- ios创建并发线程
- 老衲与你一起走过。。。
- java基础入门-----静态导入