< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Who's in the Middle

Time Limit: 1000MS

 

Memory Limit: 65536K

Total Submissions: 22341

 

Accepted: 12765

Description

FJ is surveying his herd to find the most average cow. He wants to know how much milk this 'median' cow gives: half of the cows give as much or more than the median; half give as much or less. 

Given an odd number of cows N (1 <= N < 10,000) and their milk output (1..1,000,000), find the median amount of milk given such that at least half the cows give the same amount of milk or more and at least half give the same or less.

Input

* Line 1: A single integer N 

* Lines 2..N+1: Each line contains a single integer that is the milk output of one cow.

Output

* Line 1: A single integer that is the median milk output.

Sample Input

5
2
4
1
3
5

Sample Output

3

Hint

INPUT DETAILS: 

Five cows with milk outputs of 1..5 

OUTPUT DETAILS: 

1 and 2 are below 3; 4 and 5 are above 3.

Source

USACO 2004 November

 解题报告:这就是最简单的排序问题,求中位数,为了练习堆排序,就建立了小根堆实现的,

代码如下:

复制代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
const int N = 10010;
int a[N], b[N];
void Head_adjust(int x, int y)//建立小根堆
{
int i, j, temp;
i = x;
j = 2 * i;
temp = a[i];
while (j <= y)
{
//if (j < y && a[j + 1] > a[j])//这是建立大根堆
if (j < y && a[j + 1] < a[j])
{
++ j;
}
//if (temp < a[j])//这是建立大根堆
if (temp > a[j])
{
a[i] = a[j];
i = j;
j = 2 * i;
}
else
{
break;
}
a[i] = temp;
}
}
int main()
{
int n, i, mid, m;
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
scanf("%d", &a[i]);
}
for (i = n/2; i > 0;--i)
{
Head_adjust(i, n);//将二叉树变成小根堆
}
m = n;
i = 0;
while (n --)//每次都取堆得第一个元素
{
b[i] = a[1];
i ++;
a[1] = a[n + 1];
Head_adjust(1, n);//调整
}
mid = m / 2;//因为b[]是从b[0]开始存储的,所以直接除以二就行
printf("%d\n", b[mid]);
return 0;
}
复制代码



posted on   Stephen Li  阅读(316)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示