您的位置:首页 > 其它

HDU1247 Hat’s Words (字典树)

2016-01-17 13:23 323 查看

题解:

输出字符串集合里面可以由集合里面任意两个元素组成的字符串,字典树保存暴力切割即可

代码

#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 100000
#define LL long long
int cas=1,T;
struct Tree
{
int Next[maxn][27];
int word[maxn];
int val[maxn];
int L,root;
void init()
{
L = 0;
root = newnode();
}
int newnode()
{
for (int i = 0;i<27;i++)
Next[L][i] = -1;
word[L++] = 0;
return L-1;
}
void insert(string s)
{
int l = s.size();
int u = root;
for (int i = 0;i<l;i++)
{
int c = s[i] - 'a';
if (Next[u][c] == -1)
Next[u][c] = newnode();
u = Next[u][c];
word[u]++;
}
val[u] = 1;
}
bool find(string s)
{
int u = root;
int l = s.size();
for (int i = 0;i<l;i++)
{
int c = s[i] - 'a';
if (Next[u][c] == -1)
return false;
u = Next[u][c];
}
return val[u];
}
};

char a[maxn][50];
char s1[50];
char s2[50];
int main()
{
int n = 0;
Tree tree;
tree.init();
while (gets(a
))
{
tree.insert(a
);
n++;
}

for (int i = 0;i<n;i++)
{
int l = strlen(a[i]);
for (int j = 1;j<l;j++)
{
strncpy(s1,a[i],j);
s1[j]=0;
strcpy(s2,a[i]+j);
if (tree.find(s1) && tree.find(s2))
{
printf("%s\n",a[i]);
break;
}
}
}
//freopen("in","r",stdin);
//scanf("%d",&T);
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return 0;
}


题目

Hat’s Words

Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u

HDU 1247

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: