hdu 1247

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

题意:给你一些单词,让你判断每一单词能否再给你的这些单词中找到两个不同的单词组成,如果能就输出;

理解题意后,就剩怎样查询了,在查询中我用了两成for循环解决了问题;

代码如下:

#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <cstring>
#define Max 28
using namespace std;
struct dot
{
	dot *next[Max];
	int flag;
};
dot root;
dot *newnode()
{
	dot *temp=new dot;
	temp->flag=0;
	for(int i=0;i<Max;i++)
	   temp->next[i]=NULL;
    return temp;
}
void creatree(char *st)
{
	int len=strlen(st);
	int id=0;
	dot *p=&root;
	for(int i=0;i<len;i++)
	{
		id=st[i]-'a';
        if(p->next[id]==NULL)
            p->next[id]=newnode();
        p=p->next[id];
	}
    p->flag=1;
}
int find(char *st)
{
	int len=strlen(st);
	int id=0;
	dot *p=&root;
	for(int i=0;i<len-1;i++)
	{
		id=st[i]-'a';
        if(p->next[id]==NULL)
           return 0; 
        p=p->next[id]; 
		if(p->flag)
		   {     dot *q=&root;
		         int k=1;
		         int im=0;
			   for(int j=i+1;j<len;j++)
			   {
				  im=st[j]-'a';
				  if(q->next[im]==NULL)
				     { k=0;
					   break;
				     }
                  q=q->next[im];
			   }
			   if(k&&q->flag)
			   	  return 1;
	       
		   } 
	}
	return 0;
}	
char st[50005][20];
int main()
{

	int i,j,k;
	while(scanf("%s",&st[i])!=EOF)
		creatree(st[i++]);
	for(j=0;j<i;j++)
	{   
		k=find(st[j]);
		if(k) cout<<st[j]<<endl;
	}
	return 0;
}


posted @ 2015-12-01 15:50  (慎独)  阅读(120)  评论(0编辑  收藏  举报