http://acm.nyist.net/JudgeOnline/problem.php?pid=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
-
第一行输入动物名字的数量N(1<= N <= 4000000),接下来的N行输入N个字符串表示动物的名字(字符串的长度不超过10,字符串全为小写字母,并且只有一组测试数据)。
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define NUM 26
#define change(n) (n-('a'-0))
struct Trie
{
int num;
char s[20];
struct Trie *next[NUM];
};
void Build(struct Trie *root,char *c)
{
int i,j,n,m;
struct Trie *p=root;
n=strlen(c);
for(i=0;i<n;i++)
{
m=change(c[i]);
if(p->next[m])
{
p=p->next[m];
continue;
}
//-----创建新节点-----//
struct Trie *s;
s=(struct Trie *)malloc(sizeof(struct Trie));
s->num=0;
for(j=0;j<NUM;j++)
s->next[j]=NULL;
//--------------------//
p->next[m]=s;
p=p->next[m];
}
p->num+=1;
strcpy(p->s,c);
}
int max=0;
void Erdogic(struct Trie *root)
{//递归遍历Trie树
if(root->num>max)
max=root->num;
else
{
if(!(root->next[0])&&!(root->next[1])&&!(root->next[2])&&!(root->next[3])&&!(root->next[4])&&!(root->next[5])&&!(root->next[6])&&!(root->next[7])&&!(root->next[8])&&!(root->next[9])&&!(root->next[10])&&!(root->next[11])&&!(root->next[12])&&!(root->next[13])&&!(root->next[14])&&!(root->next[15])&&!(root->next[16])&&!(root->next[17])&&!(root->next[18])&&!(root->next[19])&&!(root->next[20])&&!(root->next[21])&&!(root->next[22])&&!(root->next[23])&&!(root->next[24])&&!(root->next[25]))
return;
int i;
struct Trie *p=root;
for(i=0;i<NUM;i++)
if(p->next[i])
Erdogic(p->next[i]);
}
}
void Find(struct Trie *root)
{//找到数量是max的动物
if(root->num==max)
printf("%s %d\n",root->s,max);
else
{
if(!(root->next[0])&&!(root->next[1])&&!(root->next[2])&&!(root->next[3])&&!(root->next[4])&&!(root->next[5])&&!(root->next[6])&&!(root->next[7])&&!(root->next[8])&&!(root->next[9])&&!(root->next[10])&&!(root->next[11])&&!(root->next[12])&&!(root->next[13])&&!(root->next[14])&&!(root->next[15])&&!(root->next[16])&&!(root->next[17])&&!(root->next[18])&&!(root->next[19])&&!(root->next[20])&&!(root->next[21])&&!(root->next[22])&&!(root->next[23])&&!(root->next[24])&&!(root->next[25]))
return;
int i;
struct Trie *p=root;
for(i=0;i<NUM;i++)
if(p->next[i])
Find(p->next[i]);
}
}
void Delete(struct Trie *root)
{
int i;
for(i=0;i<NUM;i++)
{
if(root->next[i])
Delete(root->next[i]);
}
free(root);
}
int main()
{
char c[20];
int N,i,j,k;
//-----创立根节点-----//
struct Trie *head;
head=(struct Trie *)malloc(sizeof(struct Trie));
head->num=0;
for(i=0;i<NUM;i++)
head->next[i]=NULL;
//--------------------//
scanf("%d",&N);
while(N--)
{
scanf("%s",c);
Build(head,c);//构建Trie树
}
Erdogic(head);//遍历树,找到出现次数最多的max的值
Find(head);//找到数量为max的动物
Delete(head);//释放内存
return 0;
}