HDU 1247 trie 一个单词是否是两个单词的连接
2013-01-10 22:09
288 查看
#include <iostream> using namespace std; char list[50001][26]; const int kind = 26; int cnt = 0; struct Treenode { bool flag; Treenode *next[kind]; Treenode() { flag = false; for ( int i = 0; i < kind; ++i ) next[i] = NULL; } } node[100000]; //静态trie void Insert ( Treenode *&root, char *word ) { Treenode *location = root; if ( location == NULL ) { location = &node[cnt++]; root = location; } int id, i = 0; while ( word[i] ) { id = word[i] - 'a'; if ( location->next[id] == NULL ) location->next[id] = &node[cnt++]; location = location->next[id]; ++i; } location->flag = true; /*注意标记单词的最后一个字母,说明在这之前的字母组成一个单词,以便查询时划分*/ } bool check ( Treenode *root, char* word ) { Treenode *location = root; if ( location == NULL ) return false; int id, i = 0, len = strlen(word); while ( word[i] ) { id = word[i] - 'a'; if ( location->next[id] == NULL ) return false; if ( i == len-1 && location->next[id]->flag == true ) return true;/*查找到最后一个字符时,节点的标记应该是true,这样才是完全匹配的*/ location = location->next[id]; ++i; } return false; } bool Search ( Treenode *root, char * word ) { Treenode *location = root; if ( location == NULL ) return false; int id, i = 0, len = strlen(word); while ( word[i] ) { id = word[i] - 'a'; if ( location->next[id] == NULL ) return false; if ( location->next[id]->flag == true )/*当检测到一个标记时说明单词的前半部分已经检测到,现在只需检测后面一部分是否能由另一个单词构成*/ { if ( i + 1 < len && check(root,&word[i+1]) ) return true; } location = location->next[id]; ++i; } return false; } int main() { int i = 0, j; Treenode *root = NULL; while ( scanf("%s", list[i]) != EOF ) { Insert(root,list[i]); ++i; } for ( j = 0; j < i; ++j ) //将单词保存在list再搜索一遍 { if ( Search(root,list[j]) ) printf("%s\n",list[j]); } return 0; }
相关文章推荐
- 6-2-1 字符串-字符串变量String-创建字符串变量-初始化字符串变量-字符串连接-输入字符串(单词、行)-对象变量的赋值-比较两个字符串是否同一个-比较两个字符串内容是否相同
- 【HDU 1247】字典树 一个单词由两个单词组成
- 翻转子串 假定我们都知道非常高效的算法来检查一个单词是否为其他字符串的子串。请将这个算法编写成一个函数,给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成,要求只能调用一次检查子串的函数。
- 两个字符串hash问题:检查两个单词是否互为变位词和在一个字符串中第一个只出现一次的字符
- hdu 3367 Pseudoforest 伪森林 题目很难懂,模仿kruskal,并查集检查两个节点是否是一个环
- 位于两个内网的结点A和B都连接到一个公网的rdv,然后A与B之间发送消息,这时消息是否还经过rdv?
- 简单编程(十四)定义一个方法能够判断并返回两个整数的最大值,并调用自己的方法测试是否正确。
- 校验:javascript判断两个IP地址是否在同一个网段
- iOS-SQLite中怎么将两个字段字符串合并连接为一个
- 1.实现一个函数,可以左旋字符串中的k个字符。 AABCD左旋一个字符得到ABCDA AABCD左旋两个字符得到BCDAA 2.判断一个字符串是否为另外一个字符串旋转之后的字符串。 例如:给定s1
- Sql Server 中如果使用TransactionScope开启一个分布式事务,使用该事务两个并发的连接会互相死锁吗
- 写一个函数,将两个字符串连接
- 一个数是否由两个质数组成——SGU113 Nearly prime numbers
- HDU 1247 Hat’s Words(字典树Trie)
- 紫书章七例五 Krypton Factor UVA - 129(dfs)判断一个字符串中是否包含两个相邻子串
- 两个结构相同的表通过union连接称为一个表,然后在对新的表进行处理
- javascript判断两个IP地址是否在同一个网段的实现思路
- 同一个sql语句,连接两个数据库服务器
- Android实现一个apk连接两个ble设备
- (hdu step 9.1.1)A == B ?(在这个数字有可能是大数并且存在无效0的情况下,判断这两个数字是否相等)