• Poj 2388 Who's in the Middle


    1.Link:

    http://poj.org/problem?id=2388

    2.Content:

    Who's in the Middle
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 31854   Accepted: 18541

    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

    3.Method:

    4.Code:

     1 #include "iostream"
     2 #include "stdlib.h"
     3 #include "stdio.h"
     4 #include <time.h>
     5 #define N 10002
     6 using namespace std;
     7 int a[N];
     8 int Partition(int a[],int p,int r)
     9 {
    10     int tmp = a[p];
    11     while(p<r)
    12     {
    13         while(p<r && a[r]>=tmp) r--;
    14         a[p]=a[r];
    15         while(p<r && a[p]<=tmp) p++;
    16         a[r]=a[p];
    17     }
    18     a[p]=tmp;
    19     return p;
    20 }
    21 int RandomizePartition(int a[],int p,int r)
    22 {
    23     int i = rand()%(r-p+1)+p;
    24     int tmp=a[i];
    25     a[i]=a[p];
    26     a[p]=tmp;
    27     return Partition(a,p,r);
    28 }
    29 
    30 int RandomizedSelect(int a[],int p,int r,int k)
    31 {
    32     if(p==r) return a[p];
    33     int i = RandomizePartition(a,p,r),j = i-p+1;
    34     if(k<=j) return RandomizedSelect(a,p,i,k);
    35     else return RandomizedSelect(a,i+1,r,k-j);
    36 }
    37 int main()
    38 {
    39     srand(time(NULL));//初始化随机数生成器
    40     int n;
    41     int i;
    42     scanf("%d",&n);
    43     for(i=0;i<n;i++) scanf("%d",&a[i]);
    44     //qsort(a,0,n-1);
    45     //printf("%d
    ",a[n/2]);
    46     printf("%d
    ",RandomizedSelect(a,0,n-1,(n+1)/2));
    47     system("pause");
    48     return 0;
    49 }

    5.Reference:

  • 相关阅读:
    面试题 16.07. 最大数值
    461. 汉明距离
    1290. 二进制链表转整数
    1486. 数组异或操作
    1480. 一维数组的动态和
    面试题 17.04. 消失的数字
    626. 换座位
    125. 验证回文串
    530. 二叉搜索树的最小绝对差
    ASP.NET页面之间传递值的几种方式
  • 原文地址:https://www.cnblogs.com/mobileliker/p/3937175.html
Copyright © 2020-2023  润新知