HDU 1247:Hat’s Words(字典树)

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.
 

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


题意:给一些单词(以字典序输入),找出那些可以分成另外的两个单词的单词,以字典序输出;


源代码:(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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值