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



  • 相关阅读:
    02.ZooKeeper的Java客户端使用
    01.ZooKeeper安装和介绍
    02.Elasticsearch入门
    01.Elasticsearch安装
    01.ActiveMQ安装部署
    springboot项目打包时提示“程序包xxx不存在,找不到符号”
    Eclipse提交git代码 报错authentication not supported
    Eclipse提交git代码 报错authentication not supported
    utf8mb4_general_ci报错解决方案
    mysql开启远程访问
  • 原文地址:https://www.cnblogs.com/lidaojian/p/2414272.html
Copyright © 2011-2022 走看看