hdu3460

本文探讨了字典树算法在解决单词计数问题上的应用,包括两种方法:一种是通过构建字典树来计算节点数并进行调整,另一种是先对所有单词进行排序再遍历。文中提供了字典树算法的实现代码,详细解释了两种方法的时间复杂度和空间复杂度,并对比了它们在实际运行中的表现。
/*
分析:
    两个方法:
    1、建立字典树:ans=2*节点数+n(因为要输出n次)-最长链长度。
用贪心的想法想局部,然后跳出来全局看,就得到这个结论了;
    2、将所有的单词按字典序排序,然后遍历;


    前者;62MS,29688K(中途释放的话会小很多很多),1091B
    后者:31MS,736K,628B


    下面是前者的代码。


                                                    2012-07-05
*/








#include"stdio.h"
#include"string.h"
#include"stdlib.h"


struct dic
{
	struct dic *child[26];
};
struct dic *root;
int max;
int ans;


void insert(char *source)
{
	struct dic *now,*newnode;
	int i,j;
	int len;


	len=strlen(source);
	max=max>len?max:len;
	now=root;


	for(i=0;i<len;i++)
	{
		if(now->child[source[i]-'a']!=NULL)	now=now->child[source[i]-'a'];
		else
		{
			newnode=(struct dic*)malloc(sizeof(struct dic));
			for(j=0;j<26;j++)	newnode->child[j]=NULL;
			now->child[source[i]-'a']=newnode;
			now=newnode;
		}
	}
}


void count(struct dic *now)
{
	int j;


	for(j=0;j<26;j++)
	{
		if(now->child[j]==NULL)	continue;
		else
		{
			ans++;
			count(now->child[j]);
		}
	}
}


int main()
{
	int n;
	int i,j;
	char str[55];


	while(scanf("%d",&n)!=-1)
	{
		root=(struct dic *)malloc(sizeof(struct dic));
		for(j=0;j<26;j++)	root->child[j]=0;


		max=0;
		for(i=0;i<n;i++)
		{
			scanf("%s",str);
			insert(str);
		}


		ans=0;
		count(root);
		ans*=2;
		ans-=max;
		ans+=n;


		printf("%d\n",ans);
	}
	return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值