日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

NYOJ 286 动物统计

發布時間:2025/3/16 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 NYOJ 286 动物统计 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

動物統計

時間限制:1000?ms ?|? 內存限制:65535?KB 難度:2 描述

????? 在美麗大興安嶺原始森林中存在數量繁多的物種,在勘察員帶來的各種動物資料中有未統計數量的原始動物的名單。科學家想判斷這片森林中哪種動物的數量最多,但是由于數據太過龐大,科學家終于忍受不了,想請聰明如你的ACMer來幫忙。

輸入
第一行輸入動物名字的數量N(1<= N <= 10000),接下來的N行輸入N個字符串表示動物的名字(字符串的長度不超過10,字符串全為小寫字母,并且只有一組測試數據)。
輸出
輸出這些動物中最多的動物的名字與數量,并用空格隔開(數據保證最多的動物不會出現兩種以上)。
樣例輸入
10 boar pig sheep gazelle sheep sheep alpaca alpaca marmot mole

樣例輸出

sheep 3


法一:常規寫法:用一個結構體存儲動物的名字,按照字典序排序,再一個一個比較。

#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; struct animal {char s[10]; }a[ 10005]; bool cmp(animal a1,animal a2) {return strcmp(a1.s,a2.s)<0; } int main() {int n,i,cnt,max=-1;char str[10];scanf("%d",&n);for(i=0;i<n;i++)scanf("%s",a[i].s);sort(a,a+n,cmp);cnt=1;for(i=0;i<n-1;i++){if(strcmp(a[i+1].s,a[i].s)==0)cnt++;elsecnt=1;if(cnt>max){max=cnt;strcpy(str,a[i].s);}}printf("%s %d\n",str,max);return 0; }法二:用C++中的string類存儲動物名字,排序后比較。

#include<iostream> #include<string> #include<algorithm> using namespace std; int main() {string s[10005],name;int n,i,cnt=1,max=-1;cin>>n;for(i=0;i<n;i++)cin>>s[i];sort(s,s+n);for(i=0;i<n-1;i++){if(s[i+1]==s[i])cnt++;elsecnt=1;if(cnt>max){max=cnt;name=s[i];}}cout<<name<<" "<<max<<endl;return 0; }
法三:字典樹。

#include<stdio.h> #include<string.h> #include<stdlib.h> struct node {int num;struct node *next[26]; }; struct node *root; node *build() {struct node *p=(node *)malloc(sizeof(node));p->num=1;for(int i=0;i<26;i++)p->next[i]=NULL;return p; } int insert(char *s) {struct node *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']=build();p=p->next[s[i]-'a']; }return p->num++; } int main() {int n,i,max=-1,a;char str[10],s[10];root=build();scanf("%d",&n);for(i=0;i<n;i++){scanf("%s",str);a=insert(str);if(a>max){max=a;strcpy(s,str); }}printf("%s %d\n",s,max);return 0; }
法一和法二只能在數據比較少的情況下使用,如果數據很多,則要用字典樹來解,不然會超時。

總結

以上是生活随笔為你收集整理的NYOJ 286 动物统计的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。