nyoj_290动物统计加强版

在美丽大兴安岭原始森林中存在数量繁多的物种,在勘察员带来的各种动物资料中有未统计数量的原始动物的名单。科学家想判断这片森林中哪种动物的数量最多,但是由于数据太过庞大,科学家终于忍受不了,想请聪明如你的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>  
 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内存。因为要排序,运算符重载。。。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值