題目1004:Median

來源:互聯網
上載者:User

標籤:style   blog   color   os   strong   資料   

題目描述:

    Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1={11, 12, 13, 14} is 12, and the median of S2={9, 10, 15, 16, 17} is 15. The median of two sequences is defined to be the median of the non-decreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.
    Given two increasing sequences of integers, you are asked to find their median.

輸入:

    Each input file may contain more than one test case.
    Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (≤1000000) is the size of that sequence. Then N integers follow, separated by a space.
    It is guaranteed that all the integers are in the range of long int.

輸出:

    For each test case you should output the median of the two given sequences in a line.

範例輸入:
4 11 12 13 145 9 10 15 16 17
範例輸出:
13

-----------------------------------------------------------------------------------------------------------------------

思路:

  • 用一維數組來儲存資料。由於該數組很大,應該考慮用儘可能少的數組來實現以減少記憶體消耗。並且,該數組只能作為全域變數,不能再main函數定義
  • scanf函數讀取資料,只有按下斷行符號時資料才會從記憶體到所要讀取資料的變數。對於這段程式:
      while(scanf("%d",&s[0])!=EOF)   {        for(i=1;i<=s[0];i++)            scanf("%d",&s[i]);

      }

    輸入一串資料時,按下斷行符號之後,首先讀s[0],for迴圈就有了結束條件了~

------------------------------------------------------------------------------------------------------------------

 

 

 1 #include<stdio.h> 2 #define N 1000001 3 long s[2000002]; 4 int main(int argc, char const *argv[]) 5 { 6     int i,j,t; 7     long m,n; 8     while(scanf("%d",&s[0])!=EOF) 9     {10         m=s[0];11         for(i=1;i<=m;i++)12             scanf("%d",&s[i]);13         if(scanf("%d",&s[m+1])==EOF)14             break;15         n=s[m+1];16         for(i=m+2;i<=n+m+1;i++)17             scanf("%d",&s[i]);18         s[0]=m+n;19         for(i=m+1;i<m+n+1;i++)20             s[i]=s[i+1];21         for(i=1;i<m+n;i++)22             for(j=i+1;j<=m+n;j++)    23                 if(s[i]>s[j])24                 {25                     t=s[i];26                     s[i]=s[j];27                     s[j]=t;28                 }29         t=(s[0]+1)/2;30         printf("%ld\n",s[t]);31     }32     return 0;33 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.