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 nondecreasing 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.
Input
Each input file contains 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.
Output
For each test case you should output the median of the two given sequences in a line.
Sample Input4 11 12 13 14 5 9 10 15 16 17Sample Output
13
注意点:因为给出的数据很有特点(已经有序),用快速排序的话时间复杂度为O(NlogN)还是有两个测试点通不过,通过可并排序的方法的时间复杂度为O(N+M)可以AC,注意不要用C++的流来完成数据的输入,会有很多测试点超时,要用stdio.h库的scanf()和printf()来完成
参考代码:
#include <iostream> #include <stdio.h> using namespace std; int main() { int M,N; scanf("%d",&M); int *arr1 = new int[M]; for(int i=0;i<M;i++){ scanf("%d",arr1+i); } scanf("%d",&N); int *arr2 = new int[N]; for(int i=0;i<N;i++){ scanf("%d",arr2+i); } int K = M+N; int *arr3 = new int[K]; int start = 0,p1=0,p2=0; while(p1!=M || p2!=N){ if(p1==M){ arr3[start++] = arr2[p2++]; continue; } if(p2==N){ arr3[start++] = arr1[p1++]; continue; } if(arr1[p1]<arr2[p2]){ arr3[start++] = arr1[p1++]; }else{ arr3[start++] = arr2[p2++]; } } if(K%2==0) printf("%d",arr3[K/2-1]); else printf("%d",arr3[K/2]); return 0; }