【题述】
Description
问题描述:
给定含有n个元素的多重集合S,每个元素在S中出现的次数称为该元素的重数。多重集S中重数最大的元素称为众数。
例如,S={1,2,2,2,3,5}。多重集S的众数是2,其重数为3。
编程任务:
对于给定的由n 个自然数组成的多重集S,编程计算S 的众数及其重数。Input
第1行多重集S中元素个数n(n<=50000);接下来的n 行中,每行有一个自然数。
Output
输出文件有2 行,第1 行给出众数,第2 行是重数。(如果有多个众数,只输出最小的)
题意:
多组输入n,输入n个数,找出其中出现次数最多的数x(相同情况下取x中的最小值),以及x的出现次数y;
难点:
没有什么难点,水题一道。
【9.5更新,用了一点hash】
回顾了下以前的代码,完全不觉得是自己写的...现在更新了自己的代码,感觉怎么还是以前写的好呢...挠头
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#define ll long long
#define li long int
using namespace std;
const int maxn = 50000 + 5;
int a[maxn],b[maxn];
int main(){
int n;
cin>>n;
for(int i = 0 ; i < n; i++)
{
int x;
cin>>x;//hash
a[x] ++;
}
int cnt_max = -1;
for(int i = 0;i < maxn;i++)//这里不要用sort,不然原有的数据会丢失,只能保存出现的次数
{
if(a[i] > cnt_max )
cnt_max = a[i];//找到出现的最大次数
}
int tmp = 0;
for(int i = 0;i < maxn;i++)
{
if(a[i] == cnt_max )//找到那些出现次数都为最大次数的数,从里面选出最小的
b[tmp ++] = i;
}
sort(b,b + tmp);
cout<<b[0]<<endl;
cout<<cnt_max<<endl;
return 0;
}
【原来的代码】
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int main() {
int i,n,j,count,r,t,ri;
while(cin>>n){
int a[n],b[n];
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(ri=0;ri<n;ri++){
cin>>a[ri];
}
for(i=0;i<n;i++){
count=1;//注意,这里从1开始计数,因为它本身也要数进去
for(j=i+1;j<n;j++){
if(a[i]==a[j])
count++;
}
b[i]=count;
}
int max=b[0];
for(r=1;r<n;r++){
if(b[r]>max){
max=b[r];
t=a[r];
}
}
cout<<t<<endl<<max<<endl;
}
return 0;
}