您的位置:首页 > 其它

字典树典型应用(1247)

2016-05-20 19:59 302 查看

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 12639 Accepted Submission(s): 4521



[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
Your output should contain all the hat’s words, one per line, in alphabetical order.

[align=left]Sample Input[/align]

a
ahat
hat
hatword
hziee
word


[align=left]Sample Output[/align]

ahat
hatword


/*------------------Header Files------------------*/
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <ctype.h>
#include <cmath>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <vector>
#include <set>
#include <limits.h>
using namespace std;
/*------------------Definitions-------------------*/
#define LL long long
#define uLL unsigned long long
#define PI acos(-1.0)
#define INF 0x3F3F3F3F
#define MOD 9973
#define MAX 105
#define lson rt<<1,l,m
#define rson rt<<1|1,m+1,r
/*---------------------Work-----------------------*/
char word[50050][30];
struct node
{
bool isWord;
node *next[30];
node()
{
isWord=false;
memset(next,0,sizeof(next));
}
};
void insert(node *rt,char *s)
{
int i=0;
node *p=rt;
while(s[i])
{
int temp=s[i++]-'a'; //所属分支
if(p->next[temp]==NULL)
p->next[temp]=new node();
p=p->next[temp];
}
p->isWord=true;
}
bool searchWord(node *rt,char *s)
{
stack<int>mystack;
int i=0;
node *p=rt;
while(s[i])
{
int temp=s[i++]-'a';
if(p->next[temp]==NULL) return false;
p=p->next[temp];
if(p->isWord&&s[i])
mystack.push(i);
}
while(!mystack.empty())
{
bool flag=true;
i=mystack.top();
mystack.pop();
p=rt;
while(s[i])
{
int temp=s[i++]-'a';
if(p->next[temp]==NULL)
{
flag=false;
break;
}
p=p->next[temp];
}
if(flag&&p->isWord) return true;
}
return false;
}
void work()
{
int i=0;
node *rt=new node();
while(scanf("%s",word[i])==1)
{
insert(rt,word[i]);
i++;
}
//for(int j=0;j<i;j++)
//	printf("%s\n",word[j]);
for(int j=0;j<i;j++)
if(searchWord(rt,word[j]))
printf("%s\n",word[j]);
}
/*------------------Main Function------------------*/
int main()
{
//freopen("test.txt","r",stdin);
work();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: