您的位置:首页 > 其它

众数问题

2018-01-18 20:27 148 查看

                               众数问题

时间限制:3000 ms  |  内存限制:65535 KB 难度:3描述 所谓众数,就是对于给定的含有N个元素的多重集合,每个元素在S中出现次数最多的成为该元素的重数,
多重集合S重的重数最大的元素成为众数。例如:S={1,2,2,2,3,5},则多重集S的众数是2,其重数为3。
现在你的任务是:对于给定的由m个自然数组成的多重集S,计算出S的众数及其重数。
输入第一行为n,表示测试数据组数。(n<30)
每组测试的第一行是一个整数m,表示多重集S中元素的个数为m
接下来的一行中给出m(m<100)个不大于10万的自然数
(不会出现不同元素出现的次数相同的情况,如:S={11,11,22,22,33,33})。
输出每组测试数据输出一行,包含两个数,第一个是众数,第二个是其重数,中间以空格隔开。样例输入
1
6
1 2 2 2 3 5
样例输出
2 3
#include<iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n, a[100001] = { 0 }, b, max = 0, k;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> b;
a[b]++;
if (a[b] > max)
{
max = a[b];
k = b;
}
}
cout << k << " " << max<< endl;
}
return 0;
}
另一种

#include<iostream>
#include<cmath>
#include<map>
#include<algorithm>
using namespace std;

bool myless(const pair<int,int>& p1,const pair<int,int>& p2)
{
return p1.second<p2.second;
}
int main()
{
//freopen("in.txt","r",stdin);
int n;
cin>>n;
while(n--)
{
int w,a;
map<int,int> mp;
cin>>w;
while(w--)
{
cin>>a;
++mp[a];
}
map<int,int>::iterator it=max_element(mp.begin(),mp.end(),myless);
cout<<it->first<<" "<<it->second<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: