HDU-1247 Hat’s Words【字典树(逆向思维)】

 F - Hat’s Words

Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u

 
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

  1. 题意:给你n个按字典序排列的单词,问你其中的所有能由另外两个单词组成的单词并按字典序输出;
  2. 思路:先建好字典树,然后枚举一个单词将其拆分成两个单词并查询字典树中是否有这两个单词;
  3. 失误:没有想到该怎样枚举,只想选一个单词另外两个怎么选,该弄多少个循环呀,看了别人的方法才知道将这个单词拆分成两个单词;还了解了strncpy,一些字符函数能用则用,本来就是为了方便!
  4. 代码如下:

#include<cstdio>
#include<cstring>
using namespace std;

const int MAXN=1e5+10;
char str[MAXN][83];//一行好像是81个字符 
 
struct Node{
	bool flag;//标记是否以此字符结尾 
	Node *son[26]; 
}; 
Node *root;

void init(Node *p)
{
	p->flag=false; 
	int i=0;
	for(i=0;i<26;++i) p->son[i]=NULL;
}

void delet(Node *root)
{
	int i=0;
	for(i=0;i<26;++i) 
	{
		if(root->son[i]!=NULL) delet(root->son[i]);
	}
	delete(root);
}

void insert(char *str)
{
	int i=0; Node *p1=root,*p2;
	while(str[i]!='\0')
	{
		int pos=str[i]-'a';
		if(p1->son[pos]==NULL)
		{
			p2=new Node;
			init(p2);
			p1->son[pos]=p2;
		}
		p1=p1->son[pos];
		++i;
	}
	p1->flag=true;
}
 
bool find(char str[])
{
	int i=0; Node *p=root;
	while(str[i])
	{
		int pos=str[i]-'a';
		if(p->son[pos]==NULL) return false;
		p=p->son[pos]; ++i;
	}
	return p->flag;
}

int main()
{
	
	int cnt=0,i,l,j; root=new Node; init(root);
    while(gets(str[++cnt]),strcmp(str[cnt],""))//竟然测试没输出也过了 我都惊呆了
	{
		insert(str[cnt]);//gets()没问题 需要注意的是%c 也不是getchar() 
	}                   //主要用他们用怕了 %c读入慢 最好不要用 
	for(i=1;i<=cnt;++i)
	{
		int l=strlen(str[i]);
		char s1[83],s2[83];
		for(j=0;j<l;++j)
		{
			strncpy(s1,str[i],j+1); s1[j+1]='\0';//指定个数字符赋值
			strncpy(s2,str[i]+j+1,l-j-1); s2[l-j-1]='\0';
			if(find(s1)&&find(s2))
			{
				puts(str[i]); break;
			}
		}
	}
	delet(root);//加上释放空间的函数内存肯定用的少 但时间又上去了 
    return 0;   //具体问题中还需仔细斟酌 时空不可得兼呀 
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值