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.
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.
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
题解:建立字典树再暴力查找两个单词。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct Node
{
bool isStr;
Node* next[26];
Node()
{
isStr = false;
for(int i = 0;i < 26;i++)
{
next[i] = NULL;
}
}
};
char S[500005][105];
Node* root;
void insert(char* s)
{
Node* p = root;
int len = strlen(s);
for(int i = 0;i < len;i++)
{
int x = s[i] - 'a';
if(p->next[x] == NULL)
{
Node* q = new Node();
p->next[x] = q;
}
p = p->next[x];
}
p->isStr = true;
}
bool find2(char* s)
{
Node* p = root;
int len = strlen(s);
for(int i = 0;i < len;i++)
{
if(p->next[s[i] - 'a'] == NULL)
{
return false;
}
p = p->next[s[i] - 'a'];
}
return p->isStr;
}
bool find(char* s)
{
int cnt = 0;
int len = strlen(s);
Node* p = root;
for(int i = 0;i < len;i++)
{
p = p->next[s[i] - 'a'];
if(p->isStr)
{
if(i == len - 1)
{
return false;
}
if(find2(s + i + 1))
{
return true;
}
}
}
return false;
}
void del(Node*& root)
{
for(int i = 0;i < 26;i++)
{
if(root->next[i] != NULL)
{
del(root->next[i]);
}
}
delete root;
}
int main()
{
int i = 0;
root = new Node();
while(scanf("%s",S[i]) != EOF)
{
insert(S[i++]);
}
int j = 0;
while(j < i)
{
if(find(S[j]))
{
printf("%s\n",S[j]);
}
j++;
}
del(root);
return 0;
}
map +string:(G++爆内存)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
using namespace std;
map<string,int> mp;
string s[500005];
int main()
{
int n = 0;
while(cin>>s[n])
{
mp[s[n++]] = 1;
}
for(int i = 0;i < n;i++)
{
for(int j = 1;j < s[i].size() - 1;j++)
{
string s1(s[i],0,j);
string s2(s[i],j);
if(mp[s1] == 1 && mp[s2] == 1)
{
printf("%s\n",s[i].c_str());
break;
}
}
}
return 0;
}