hdu1247Hat’s Words(字典树---判断单词有无组合现象)

本文提供了一道ACM竞赛编程题的解决方案,采用字典树(Trie)进行字符串匹配和检索,通过构建字典树来高效地实现字符串集合的查询操作。

1.题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1247

 

2.参考代码:

 

#include <cstdio>
#include <cstring>

struct node{
	int flag;   ///标记是否到达树的尾部
	node* next[26];
	node(){
		flag=0;
		memset(next,0,sizeof(next));
	}
};

node* root=NULL;

void build(char* s){   ///建树
	node* p=root;
	int len=strlen(s);
	for(int i=0;i<len;i++)
	{
		if(!p->next[s[i]-'a'])
			p->next[s[i]-'a']=new node;
		p=p->next[s[i]-'a'];
	}
	p->flag=1;   ///标记已到达单词尾部
}

int find(char* s){   ///查找
	node* p=root;
	int len=strlen(s);
	for(int i=0;i<len;i++)
	{
		if(!p->next[s[i]-'a'])
			return 0;
		p=p->next[s[i]-'a'];
	}
	if(p->flag)   ///判断是否已经到达最后一个字母,避免只有前部分的相同
		return 1;
	else
		return 0;
}

void Delete(node* p){
for(int i=0;i<10;i++)

  {
		if(!p->next[i])
		Delete(p->next[i]);
		}
		delete p;
}

int main()
{
	root=new node;
	int i,j,k,c=0;
	char str[50001][20];
//	while(gets(str[c]))   ///不能用gets()接收
    while(~scanf("%s",str[c]))
	{
		build(str[c]);
		c++;
	}
	for(i=0;i<c;i++)
	{
		int len=strlen(str[i]);
		int count=0,x,y;
		char a[20],b[20];
		for(j=0;j<len;j++)   ///将字符串分段检索
		{
			count++;   ///计算单词个数
			x=0;
			y=0;   ///x和y是计算拆分后2个单词的个数
			for(k=0;k<len;k++)
			{
				if(k<count)
					a[x++]=str[i][k];
				else
					b[y++]=str[i][k];
			}
			a[x]='\0';   ///单词最后的'\0'别忘了
			b[y]='\0';
			if(find(a) && find(b))
			{
				printf("%s\n",str[i]);
				break;
			}
		}
	}
	Delete(root);
	return 0;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值