您的位置:首页 > 其它

HDU 1247 Hat’s Words

2016-08-27 17:38 495 查看
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


题意:  给出若干个单词,找出其中能够由其它两个单词连接组合而成的单词

 

每个单词进行切分,把切分得到的两个单词在原单词序列中查找,若能查到则符合条件。

既可以用map<string, int>实现  也可以用Trie树实现

用map很容易 但为了学习Trie树 就用了Trie树实现

参考 http://blog.csdn.net/azheng51714/article/details/7836687

  http://www.cnblogs.com/pony1993/archive/2012/07/18/2596730.html
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <stack>
#include <string>
#include <map>
#include <set>
#define pi acos(-1.0)
#define LL long long
#define ULL unsigned long long
#define inf 0x3f3f3f3f
#define INF 1e18
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mem0(a) memset(a, 0, sizeof(a))
#define memi(a) memset(a, inf, sizeof(a))
#define mem1(a) memset(a, -1, sizeof(a))
using namespace std;
typedef pair<int, int> P;
const double eps = 1e-10;
const int maxn = 5e4 + 5;
const int mod = 1e8;
const int N = 26;

struct Node
{
int flag;
Node* next
;
Node(){
flag = 0;
for (int i = 0; i < N; i++)
next[i] = NULL;
}
}tree[maxn];
int node;
Node* Creat()
{
Node* p = &tree[node++];
return p;
}
void Insert(Node* root, char* s)
{
Node* p = root;
for (int i = 0; i < strlen(s); i++){
int k = s[i] - 'a';
if (p->next[k] == NULL)
p->next[k] = Creat();
p = p->next[k];
}
p->flag = 1;
}
int Search(Node* root, char* s)
{
Node* p = root;
for (int i = 0; i < strlen(s); i++){
int k = s[i] - 'a';
if ((p->next[k]) == NULL)
return 0;
p = p->next[k];
}
return p->flag;
}
char s[maxn][105];
char s1[105], s2[105];
int main(void)
{
//	freopen("C:\\Users\\wave\\Desktop\\NULL.exe\\NULL\\in.txt","r", stdin);
int c = 0, i, j, k, len;
node = 0;
Node* root = Creat(); // 建立根节点
while (~scanf("%s", &s[c]))
Insert(root, s[c++]);
for (k = 0; k < c; k++){
len = strlen(s[k]);
memset(s1, 0, sizeof(s1));
for (i = 0; i < len; i++){  // 分两半
s1[i] = s[k][i];
if (!Search(root, s1)) continue;
memset(s2, 0, sizeof(s2));
for (j = i+1; j < len; j++)
s2[j-i-1] = s[k][j];
if (!Search(root, s2)) continue;
puts(s[k]);
break;
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: