0%

Hdu 1247 - Hat’s Words (字典树)

题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1247

题目大意:
给出一个单词表,询问其中是否存在某些单词,如hat-word,是由表中其他两个单词拼接得到的,输出所有的这样的单词

分析:
直接将单词全部插入字典树,然后暴力枚举每个单词的所有分割可能即可

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
#include<map>
#include <string>
using namespace std;

typedef long long ll;


struct Trie{
Trie *next[26];
int val;
Trie(){
val = -1;
for (int i = 0 ; i < 26 ; i ++)
next[i] = NULL;
}
};

void addword(string& str,Trie* node,int i)
{
if (node->next[str[i]-'a']==NULL)
node->next[str[i]-'a'] = new Trie;

node = node->next[str[i]-'a'];
++i;
if (i<str.size())
addword(str,node,i);
else
{
node->val = 1;
return;
}
}


int query(string & str ,Trie *node,int i)
{
if (node->next[str[i]-'a']==NULL)
return -1;
else
node= node->next[str[i]-'a'];
++i;
if (i<str.size())
return query(str,node,i);
else
return node->val;
}

string str[100000];


int main()
{
int cnt=0;
string p,q;
Trie* head = new Trie;
ios::sync_with_stdio(false);
while (cin>>str[cnt])
{
addword(str[cnt],head,0);
cnt++;
}
sort(str,str+cnt);
for (int i = 0 ; i < cnt ; i ++)
{
p.clear();
q.clear();
for (int j = 0 ; j < str[i].size()-1 ;j ++)
{
p +=str[i][j];
q = str[i].substr(j+1);
//cout<<" p = "<<p<<" q = "<<q<<endl;
if (query(p,head,0)!=-1&&query(q,head,0)!=-1)
{
cout<<str[i]<<endl;
break;
}
}
}



return 0;
}