soj 1796. Max's kingdom

来源:互联网 发布:linux查看登录用户清单 编辑:程序博客网 时间:2024/05/20 19:15

描述:

有N(1 <= N <= 10000)个人,给出他们来自的星球p(1 <= p <= 1.5e9,整数)和智力值a(|a| < 1.5e9,整数),求所有出现的星球的智力值。

星球的智力值定义如下:

如果星球有偶数个人,那么星球的智力值为中间两个人的智力均值(下取整)

如果星球有奇数个人,那么星球的智力值为中间一个人的智力值。

思路:

根据数据规模,选取map <int, vector<LL> >作为数据结构,排序即可。

注意点:

用long long而非存智力值,防止相加溢出int(由于智力值可能是负值,故(a-b)/2 + b也不适用)。

代码:

#include <cstdio>#include <vector>#include <map>#include <algorithm>using namespace std;typedef long long LL;int n, p, a;map <int, vector <LL> > planet;map <int, vector <LL> >::iterator it;LL Mid(vector <LL> &v){int s = v.size();if (s & 1) return v[s/2];else return int((v[s/2] + v[s/2-1]) / 2);}int main(){while (~scanf("%d", &n)){planet.clear();while (n --){scanf("%d %lld", &p, &a);planet[p].push_back(a);}for (it = planet.begin(); it != planet.end(); ++ it){sort(it->second.begin(), it->second.end());printf("%d %lld\n", it->first, Mid(it->second));}}}

原创粉丝点击