nyoj 290 动物统计加强版 字典树

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int max=0;
char ans[20];
struct node//结点
{
	int count;
	struct node *next[26];//每个结点有26个分支
};
struct node *root;//根结点
struct node *newset()
{
	struct node *p;
	p=(struct node *)malloc(sizeof(struct node));//动态分配内存
    for(int i=0;i<26;i++)
	{
		p->next[i]=NULL;//结点置空
	}
	p->count=0;//计数器的值置为0
	return p;
}
void insert(char *s)//插入
{
	struct node *p;
    p=root;
	int len=strlen(s);
	for(int i=0;i<len;i++)
	{
		if(p->next[s[i]-'a']==NULL)//判断是否为空
			p->next[s[i]-'a']=newset();
         p=p->next[s[i]-'a'];
	}
	p->count++;
	if(p->count>max)
	{	max=p->count;
	strcpy(ans,s);//保存最长的字符串
	}
}
int main()
{
	int n;
	char chr[12];
	root=newset();
	scanf("%d",&n);
	while(n--)
	{
     scanf("%s",chr);
	 insert(chr);
	}
	printf("%s %d\n",ans,max);
	return 0;
}         

字典树经典题目

刚开始学习字典树的朋友们可以看一下我队友的博客http://www.imanor.net/?p=277



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值