NYOJ 290

本文介绍了一种用于统计大量动物名称并找出出现次数最多的动物及其数量的算法。通过使用前缀树数据结构,该算法能高效地处理数百万级别的数据集。

动物统计加强版

时间限制:3000 ms  |  内存限制:150000 KB
难度:4
描述
在美丽大兴安岭原始森林中存在数量繁多的物种,在勘察员带来的各种动物资料中有未统计数量的原始动物的名单。科学家想判断这片森林中哪种动物的数量最多,但是由于数据太过庞大,科学家终于忍受不了,想请聪明如你的ACMer来帮忙。
输入
第一行输入动物名字的数量N(1<= N <= 4000000),接下来的N行输入N个字符串表示动物的名字(字符串的长度不超过10,字符串全为小写字母,并且只有一组测试数据)。 
输出
输出这些动物中最多的动物的名字与数量,并用空格隔开(数据保证最多的动物不会出现两种以上)。 
样例输入
10
boar
pig
sheep
gazelle
sheep
sheep
alpaca
alpaca
marmot
mole
样例输出
sheep 3
 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define N 26


typedef struct node {
	int cnt;
	struct node* next[N];
}Node, *pNode;


int count = 0;
char ans[15];


pNode creat_node() {
	pNode t = (pNode)malloc(sizeof(Node));
	int i; 


	t->cnt = 0;
	for (i = 0; i < N; i++)
		t->next[i] = NULL;
	return t;
}


void insert(pNode head, char* s) {
	int i = 0, len = strlen(s);
	pNode t = head;


	for (i = 0; i < len; i++) {
		if (t->next[s[i] - 'a'] == NULL) {
			t->next[s[i] - 'a'] = creat_node();
		}
		t = t->next[s[i] - 'a'];
	}
	t->cnt ++;
	if (t->cnt > count) {
		count = t->cnt;
		strcpy(ans, s);
	}
}


int main(){
	int n;
	scanf("%d", &n);
	char s[15];
	pNode head = creat_node();
	while (n--) {
		scanf("%s", s);
		insert(head, s);
	}
	printf("%s %d", ans, count);
	return 0;
}        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值