链接:http://acm.hust.edu.cn/vjudge/problem/18360/origin
题目: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.
题意:给出一个单词表,把所有可以用另外两个单词链接起来表示的单词打印出来。
分析:多维互相匹配,字典树的特征。存储用模板就好,查询的时候要下点功夫。对于这道题,某个单词可能不仅仅能由两个单词组成,比如。。。瞎编一个ab,abcd,cd,c,d。abcd可以是两个也可以是三个单词组成。解决办法是查找的时候,把每个分割点都记录下来,如果分割点到结尾可以组成一个单词,那么就可以被两个单词组成。问题得解。
题解:
题目: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.
题意:给出一个单词表,把所有可以用另外两个单词链接起来表示的单词打印出来。
分析:多维互相匹配,字典树的特征。存储用模板就好,查询的时候要下点功夫。对于这道题,某个单词可能不仅仅能由两个单词组成,比如。。。瞎编一个ab,abcd,cd,c,d。abcd可以是两个也可以是三个单词组成。解决办法是查找的时候,把每个分割点都记录下来,如果分割点到结尾可以组成一个单词,那么就可以被两个单词组成。问题得解。
题解:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
#define rt return 0
#define fr freopen("in.txt","r",stdin)
#define fw freopen("out.txt","w",stdout)
#define ll long long
#define detie ios_base::sync_with_stdio(false);cin.tie(false)
using namespace std;
struct Node
{
Node() :is(false), count(0) { memset(next, 0, sizeof next); }
bool is;
int count;
int next[26];
}no[100000];
string s[50010];
int root = 0;
int rl = 0;
void insert(string &s)
{
int len = s.size();
int p = root;
for (int i = 0; i < len; i++)
{
int id = s[i] - 'a';
if (!(no[p].next[id]))
no[p].next[id] = ++rl;
p = no[p].next[id];
}
no[p].is = true;
}
bool find(string &s)
{
int len = s.size();
int sta[1000];
int p = root;
int sl = 0;
for (int i = 0; i < len; i++)
{
int id = s[i] - 'a';
p = no[p].next[id];
if (no[p].is)
sta[sl++] = i+1;
}
while (sl)
{
bool flag = true;
int i = sta[--sl];
p = root;
while (i<len)
{
int id = s[i++] - 'a';
if (!(no[p].next[id]))
{
flag = false;
break;
}
p = no[p].next[id];
}
if (flag&&no[p].is)
return true;
}
return false;
}
int main()
{
//fr;
detie;
int i = 0;
//root = new Node;
while (cin>>s[i])
{
insert(s[i]);
i++;
}
int j = 0;
while (j<i)
{
if (find(s[j]))
cout << s[j] << endl;
j++;
}
rt;
}