題目1004:Median (歸併排序應用)

內存還可以優化,第二行數據不必全部讀取~

  1. #include<stdio.h> 
  2. #define MAXSIZE 1000002 
  3. int main(void
  4.     int list1[MAXSIZE],list2[MAXSIZE]; 
  5.     int n1,n2,median,res; 
  6.     int i,j,count; 
  7.     while(scanf("%d",&n1)!=EOF) 
  8.     { 
  9.         for(i=0;i<n1;i++) 
  10.         { 
  11.             scanf("%d",&list1[i]); 
  12.         } 
  13.   
  14.         scanf("%d",&n2); 
  15.         for(i=0;i<n2;i++) 
  16.         { 
  17.             scanf("%d",&list2[i]); 
  18.         } 
  19.   
  20.         median = (n1+n2-1)/2; 
  21.         count=0; 
  22.         for(i=0,j=0;i<n1&&j<n2&&count<=median;) 
  23.         { 
  24.             if(list1[i]<list2[j]) 
  25.             { 
  26.                 res = list1[i]; 
  27.                 i++; 
  28.                 count++; 
  29.             } 
  30.             else if(list1[i]>list2[j]) 
  31.             { 
  32.                 res = list2[j]; 
  33.                 j++; 
  34.                 count++; 
  35.             } 
  36.             else 
  37.             { 
  38.                 res = list1[i]; 
  39.                 i++; 
  40.                 j++; 
  41.                 count +=2; 
  42.             } 
  43.         } 
  44.         while(i==n1 && count<=median) 
  45.         { 
  46.             res = list2[j]; 
  47.             j++; 
  48.             count++; 
  49.         } 
  50.         while(j==n2 && count<=median) 
  51.         { 
  52.             res = list1[i]; 
  53.             i++; 
  54.             count++; 
  55.         } 
  56.         printf("%d\n",res); 
  57.     } 
  58.     return 0; 
  59. /************************************************************** 
  60.     Problem: 1004 
  61.     User: 1290605023 
  62.     Language: C 
  63.     Result: Accepted 
  64.     Time:10 ms 
  65.     Memory:8648 kb 
  66. ****************************************************************/ 

 

題目描述:

    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 14
5 9 10 15 16 17
樣例輸出:
13
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章