HDU 1247-Hat’s Words(trie树)

D - Hat’s Words
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Appoint description: 

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
思路:
这题的做法不错,一开始不懂题意,一直Wa,结果就是找只有另外两个单词组成的单词。
AC代码:
/*
这题一开始就写对了,结果过了样例还
是Wa了,弄了几组数据也过了,但还是
Wa了,之后又弄了一组数据就没答案了。
最后发现原来是v数组写了26,害我一直
Wa。
数据:
a
ahat
hat
hatword
hziee
word
hatwordword
aahat
aahatword
*/


#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<cmath>
typedef long long ll;
using namespace std;
#define T 55555
#define maxn 26
#define inf 0x3f3f3f3f
struct trie
{
	int kid[T][26],v[T];
	int L,root;
	trie(){
		L=1;
		root = 0;
		memset(kid[0],-1,sizeof(kid[0]));
	}
	int newnode(){
		v[L] = 0;
		memset(kid[L],-1,sizeof(kid[L]));
		return L++;
	}
	void insert(char* s){
		int p = root;
		for(int i=0;s[i];++i){
			int d = s[i] - 'a';
			if(kid[p][d]==-1){
				kid[p][d] = newnode();
			}
			p = kid[p][d];
		}
		v[p]++;
	}
	bool find(char *s)
	{
		int p = 0;
		for(int i=0;s[i];++i){
			int d = s[i]-'a';
			p = kid[p][d];
			if(p==-1)return false;
			if(v[p]&&s[i+1]=='\0')
				return true;
		}
		return false;
	}
	bool query(char* s){
		int p = root,sum=0;
		for(int i=0;s[i];++i){
			int d = s[i]-'a';
			p = kid[p][d];
			if(v[p]&&find(s+i+1)){
                 return true;
			}
		}
		return false;
	}
}tr;
char str[T][1000];
int main()
{
#ifdef zsc
 freopen("input.txt","r",stdin);
#endif
	 int n=0,i;
	 while(~scanf("%s",&str[n])){
		 tr.insert(str[n++]);
	 }
	 for(i=0;i<n;++i){
		 if(tr.query(str[i])){
			 printf("%s\n",str[i]);
		 }
	 }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值