zoukankan      html  css  js  c++  java
  • The median of multi ascending array

    Given 17 arrays,every array is ascending.The task is to get the median of all these numbers.

    0 1 2 3 4           this is an array with 5 elements,the median is (5/2).

    0 1 2 3 4 5        this is an array with 6 elements,the median is (6/2).

    If we index an the elements from 0,the median is the element's count/2.

    Input format

    5
    12
    7 13 16 20 22 53 54 55 64 71 80 95 
    10
    7 19 21 58 67 77 85 89 90 96 
    3
    22 46 51 
    3
    31 43 87 
    8
    5 10 11 35 67 75 75 88

    sort them:

    5 7 7 10 11 
    13 16 19 20 21 
    22 22 31 35 43 
    46 51 53 54 55 
    58 64 67 67 71 
    75 75 77 80 85 
    87 88 89 90 95 
    96 

    36 elements(from a[0] to a[35]).The median is the a[18](the 19th)= 54.

    The method above is O(n).

    The method below is O(lgn).The keythought in the below method is alike with trisection.

     1 #include<iostream>
     2 #include<math.h>
     3 using namespace std;
     4 int a[17][1000];
     5 int len[17];
     6 int n;
     7 int main(){
     8     int l=0;
     9     cin>>n;
    10     for(int i=0;i<n;i++){
    11         cin>>len[i];
    12         l+=len[i];
    13         for(int j=0;j<len[i];j++)cin>>a[i][j];
    14     }
    15     int rem=l-(l>>1);
    16     /*
    17     If forward l-(l/2) steps,the minimum value is the ans. 
    18     */
    19     int ans;
    20     while(rem){
    21         int s=ceil(1.0*rem/n);
    22         int mi=-10000;
    23         int ii=0;
    24         //At least,there is someone forward  ceil(rem/n) steps.who should do this?
    25         for(int i=0;i<n;i++){
    26             if(len[i]){
    27                 int j=max(0,len[i]-s);
    28                 if(a[i][j]>mi){
    29                     mi=a[i][j];
    30                     ii=i;
    31                 }
    32             }
    33         }
    34         int j=max(0,len[ii]-s); 
    35         rem-=(len[ii]-j);
    36         len[ii]=j;
    37         ans=min(ans,a[ii][j]);//I made a mistake here,should use 'min' to update ans.
    38     }
    39     cout<<ans<<endl;
    40     return 0;
    41 }
  • 相关阅读:
    第十一周总结
    第十周总结
    实验报告(七)及第九周总结
    第六次实验及第八周总结
    第五实验报告及第七周总结
    第六周&实验四
    期末课程总结
    第十四周课程总结&实验报告(简单记事本的实现)
    第十三周课程总结
    第十二周总结
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/4974841.html
Copyright © 2011-2022 走看看