Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 2205 Accepted Submission(s): 804
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
aahathathatwordhzieeword
Sample Output
ahathatword
题意:给一些单词(以字典序输入),找出那些可以分成另外的两个单词的单词,以字典序输出;
源代码:(15MS)
#include<iostream>
#include<string.h>
using namespace std;
const int NODEMAX=26;
const int MAX=50005;
char word[MAX][16]; //这道题16就足够了
struct TrieNode
{
bool is;
TrieNode *next[NODEMAX];
TrieNode()
{
is=false;
memset(next,0,sizeof(next));
}
};
void InsertTrie(TrieNode *pRoot,char s[])
{
int i;
TrieNode *p=pRoot;
i=0;
while(s[i])
{
int k=s[i]-'a';
if(p->next[k]==NULL)
p->next[k]=new TrieNode();
i++;
p=p->next[k];
}
p->is=true; //该结点是单词的尾
}
bool Search(TrieNode *pRoot,char s[])
{
int i,top=0,stack[1000];
TrieNode *p=pRoot;
i=0;
while(s[i])
{
int k=s[i++]-'a';
if(p->next[k]==NULL)
return 0;
p=p->next[k];
if(p->is && s[i]) //找到该单词含有子单词的分隔点
stack[top++]=i;//入栈
}
while(top)//从可能的分割点去找
{
bool ok=1;
i=stack[--top];
p=pRoot;
while(s[i])
{
int k=s[i++]-'a';
if(p->next[k]==NULL)
{
ok=false;
break;
}
p=p->next[k];
}
if(ok && p->is)//找到最后,并且是单词的
return 1;
}
return 0;
}
int main()
{
int i=0;
TrieNode *pRoot=new TrieNode();
while(gets(word[i]))
{
InsertTrie(pRoot,word[i]);
i++;
}
for(int j=0;j<i;j++)
if(Search(pRoot,word[j]))
cout<<word[j]<<endl;
return 0;
}