zoukankan      html  css  js  c++  java
  • POJ 2388 Who's in the Middle(堆排序)

    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;
    }



  • 相关阅读:
    Java【第二篇】基本语法之--进制、运算符
    Java【第一篇】基本语法之--关键字、标识符、变量及分类、数据类型及转换
    安装运行zookeeper的坑
    部署java应用的几种方式
    解决sudo用户找不到环境变量的问题
    Python装饰器详解
    filebeat开启自带模块收集日志如何辨别日志来源等
    使用elasticsearch7.3版本在一台主机上部署多个实例组建集群
    redis 集群搭建
    Kibana多用户创建及角色权限控制
  • 原文地址:https://www.cnblogs.com/lidaojian/p/2414272.html
Copyright © 2011-2022 走看看