(字典树)Hat’s Words -- HDOJ
来源:互联网 发布:十秒竞拍源码 编辑:程序博客网 时间:2024/06/07 13:40
Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 308 Accepted Submission(s): 142
Problem Description
A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.
Output
Your output should contain all the hat’s words, one per line, in alphabetical order.
Sample Input
a
ahat
hat
hatword
hziee
word
Sample Output
ahat
hatword
Author
戴帽子的
Recommend
Ignatius.L
/* 根据每个单词建立一棵树 对每个单词拆成两部分,分别对这两部分去树中查找, 判断是否这两部分,都在树中,若都在,则说明这个单词 是由两个单词组成的*/#include<iostream>#include<stdio.h>#include<algorithm>#include<string>#include<string.h>#include<math.h>#include<map>#include<set>#include<string>#define mod 1000000007using namespace std;typedef struct Node{ bool is; Node *nxt[27];//26个英文字母 Node() { is = false;//is为true,则代表一个单词的结束 memset(nxt,0,sizeof(nxt)); }}Node;string word[50005];void Insert(Node * root,string s){ int indx=0; Node *p = root; while(indx<s.size())//将单词的每个字母都插入到树中 { int k = s[indx++] - 'a'; if(p->nxt[k] == 0)//如果k位置不存在,我们就新生成一个节点 p->nxt[k] = new Node(); p = p->nxt[k]; } p->is = true;//单词插入结束,做标记}bool Search(Node *root,string s){ Node *p = root; int indx = 0; while(indx < s.size()) { int k = s[indx++] - 'a'; if(p->nxt[k] == 0)//要查询的第indx个字母不存在,则单词不在这个树中 return 0; p = p->nxt[k]; } if(p->is)//查询完整个单词,正好到达单词结束的标记地方 return 1; return 0;}int main(void){ // freopen("in.txt","r",stdin); int indx = 0; Node *root = new Node(); while(cin>>word[indx]) { Insert(root,word[indx++]); } for(int i=0; i<indx; ++i) { bool flg = false; for(int j=1; j<word[i].size(); ++j) { //将单词分割成两部分 string str1 = word[i].substr(0,j); string str2 = word[i].substr(j,word[i].size()-j); //其中有个为空,则不做操作 if(!str1.size() || !str2.size()) continue; //两部分都满足在树中 if(Search(root,str1) && Search(root,str2)) { flg = true; break; } } if(flg) cout << word[i]<<endl; } return 0;}
阅读全文
0 0
- (字典树)Hat’s Words -- HDOJ
- [HDOJ 1247] Hat’s Words [字典树]
- 字典树-HDOJ-1247-Hat’s Words
- hdoj-1247-Hat’s Words-字典树
- HDOJ 1247 Hat’s Words(字典树变形)
- HDOJ Hat’s Words 1247【经典字典树】
- hdu Hat‘s Words(字典树)
- Hat’s Words(字典树)
- HDU1247 Hat’s Words (字典树)
- hdu1247 Hat’s Words(字典树)
- HDU1247:Hat’s Words(字典树)
- Hat‘s Words(字典树)
- Hat’s Words(字典树)
- Hat’s Words(字典树)
- HDOJ Hat’s Words
- Hat’s Words hdu 1247(字典树 map)
- HDU 1247:Hat’s Words(字典树)
- hdu 1247 Hat’s Words(字典树)
- 按装hadoop
- 锋利的jQuery中值得记下的例子(2)
- Java之内存泄漏详解
- c/c++ 面试笔试知识点----牛客网(5)
- #7 一维数组
- (字典树)Hat’s Words -- HDOJ
- 各种类型的转换
- win2008 server r2 intel网卡驱动无法安装不存在英特尔PRO适配器的解决方法
- 深入理解JVM总结-JDK各版本、JVC内存分配及溢出异常
- NDK Build 用法(NDK Build)
- 贪吃蛇
- 【Unity3d】简单的物体漂浮算法
- php 爬虫的简单实现, 获取整个页面, 再把页面的数据导入本地的文件当中
- 机器学习——KNN实现