动物统计加强版
时间限制:
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
思路:
字典树。由于N数据量太大,导致超时,所以用字典树做。节点结构体中的 num 维护每个单词最后一个字母出现的次数,边统计边比较,最后输出最大值即可。
AC:
#include<cstdio>
#include<string.h>
using namespace std;
typedef struct no
{
struct no *next[26];
int num;
}node;
int maxnum;
char fin[10];
node *creat_node()
{
node *p = new node;
for(int i = 0;i < 26;i++)
p -> next[i] = NULL;
p -> num = 0;
return p;
}
void insert_str(char *str,node *head)
{
int len = strlen(str);
node *p = head;
for(int i = 0;i < len;i++)
{
int c = str[i] - 'a';
if(p -> next[c] == NULL)
{
node *t = creat_node();
p -> next[c] = t;
}
p = p -> next[c];
if(i == len - 1) p -> num++;
if(i == len - 1 && p -> num > maxnum)
{
strcpy(fin,str);
maxnum = p -> num;
}
}
}
int main()
{
int n;
node *head = creat_node();
scanf("%d",&n);
maxnum = 0;
while(n--)
{
char an[15];
scanf("%s",an);
insert_str(an,head);
}
printf("%s %d\n",fin,maxnum);
return 0;
}