Hat’s Words
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 6 Accepted Submission(s) : 2
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.
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
题目大意:按字典序输人的单词中是否有单词是任两个单词连接而成。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
vector<string>m;
char s[50];
int cnt = 1;
struct node
{
int a[26];
int f;
};
node tree[1000*100];
void build_tree()
{
int root = 0;
for(int i = 0; s[i]!= '\0'; i ++)
{
if(tree[root].a[s[i]-'a'] == -1)
{
tree[root].a[s[i]-'a'] = cnt ++;
}
root = tree[root].a[s[i]-'a'] ;
}
tree[root].f = 1;
}
void find_result()
{
int root , root2;
int flag ;
for(int i = 0; i < (int)m.size(); i ++)
{
flag = 0;
//cout << "test==="<<m[i]<<endl;
root = 0;
for(int j = 0; j < (int)m[i].size(); j ++)
{
if(tree[root].a[m[i][j]-'a'] != -1)
{
root = tree[root].a[m[i][j]-'a'];
if(tree[root].f == 1)
{
//cout << "first paragram=="<<m[i][j]<<endl;
root2 = 0;
int k ;
flag = 0;
for(k = j + 1; k < (int)m[i].size(); k ++)
{
if(tree[root2].a[m[i][k]-'a'] == -1)
{
break;
}
root2 = tree[root2].a[m[i][k]-'a'];
}
if(k == (int)m[i].size() && tree[root2].f == 1)
{
//cout << "second paragram===" <<m[i][k] <<endl;
printf(m[i].c_str());
printf("\n");
//cout << m[i]<<endl;
flag = 1;
}
}
}
if(flag)break;
}
}
return ;
}
int main()
{
for(int i = 0; i < 1000*100; i ++)
{
tree[i].f = 0;
for(int j = 0; j < 26; j ++)
{
tree[i].a[j] = -1;
}
}
string ss;
int n;
while(scanf("%s",s)!=EOF)
{
ss = s;
n = m.size();
build_tree();
if(n == 0)
{
m.push_back(ss);
}
else if(ss.compare(m[n-1]))
{
m.push_back(ss);
}
}
find_result();
return 0;
}