#UVa:10107-What is the Median?

灆洢 2011-11-30 13:23:15

數值一直由小到大插入陣列中,即可得其中位數。

C++(0.040)

/*******************************************************/
/* UVa 10107 What is the Median?                       */
/* Author: Maplewing [at] knightzone.studio            */
/* Version: 2011/11/30                                 */
/*******************************************************/
#include<iostream>
#include<cstdio>
using namespace std;

int main(){
  int N[10005], top = 0, temp;
  while( scanf( "%d", &N[top++] ) != EOF ){
    for( int i = 0 ; i < top ; i++ )
      if( N[top-1] > N[i] ){
        temp = N[top-1];
        for( int j = top-1 ; j > i ; j-- )
          N[j] = N[j-1];
        N[i] = temp;
        break;
      }
      if( top % 2 )
        printf( "%d\n", N[top/2] );
      else
        printf( "%d\n", (N[top/2]+N[top/2-1])/2 );
  }
  return 0;
}

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料