您的位置:首页 > 其它

集训队专题(1)1007 Hat’s Words

2016-01-27 14:56 393 查看


Hat’s Words


Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)


Total Submission(s) : 36 Accepted Submission(s) : 15


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


Author

戴帽子的

此题是字典树的一个变形(小编看网上有大神没用字典树就AC的……牛逼啊)。由于需要判断是否为一个词的结尾,故需要在结构体定义的时候加一项bool变量来判断。此题小编是先把所有的节点先建立好再进行搜索的,当然要是大神够6可以在建立节点的同时进行搜索(小编我也是个辣鸡TT,同求大神的方法)。

#include <iostream>
#include <string.h>
#include <cstdio>
#define MAX 50005
using namespace std;
char word[MAX][16];  //这道题16就足够了
struct TrieNode
{
bool is;
TrieNode *next[26];
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: