- 在美丽大兴安岭原始森林中存在数量繁多的物种,在勘察员带来的各种动物资料中有未统计数量的原始动物的名单。科学家想判断这片森林中哪种动物的数量最多,但是由于数据太过庞大,科学家终于忍受不了,想请聪明如你的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<stdlib.h>
int max;
char ans[101];
struct node
{
int count;
struct node *next[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;
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 ncases;
char str[20];
root=(struct node *)malloc(sizeof(struct node));//newset();
for(int i=0;i<26;i++)
{
root->next[i]=NULL;
}
root->count=0;
scanf("%d",&ncases);
while(ncases--)
{
scanf("%s",str);
insert(str);
}
printf("%s %d\n",ans,max);
return 0;
}
思路解析:
典型的字典树应用,俺是第一次写,有参考。我分析过了几个代码,这种是用时最少的。1624s 56408内存
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct zz
{
char str[11];
int count;
}w[4000001];
bool operator<(zz const&x,zz const&y)
{
if(strcmp(x.str,y.str)<0)
return true;
return false;
}
int main()
{
int n,i,p,max;
memset(w,0,sizeof(w));
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s",w[i].str);
w[i].count=1;
}
sort(w,w+n);
p=0;max=0;
for(i=1;i<n;i++)
{
if(strcmp(w[i].str,w[i-1].str)==0)
{
w[i].count=w[i-1].count+1;
}
if(w[i].count>max)
{
max=w[i].count;
p=i;
}
}
printf("%s %d\n",w[p].str,max);
return 0;
纯粹的字符串的处理方法。。。用时2756s,62732内存。因为要排序,运算符重载。。。