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 Specification:
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 (≤2×10^5) 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 Specification:
For each test case you should output the median of the two given sequences in a line.
Sample Input:
4 11 12 13 14
5 9 10 15 16 17
Sample Output:
13
题目大意:
给出一个有N(N <= 2 * 10^5)个数字的递增序列S,那么它的中间数字就是处在序列最中间位置的数。例如对于S1={11,12,13,14},它的中间数字是12,对于S2={9, 10, 15, 16, 17},她的中间数字是15。两个递增序列的中间数字就是包含了两个序列中所有数字的非递减序列的处于最中间位置的数,例如S1和S2的中间数字是13。
现给出两个序列,要求你求出这两个序列的中间数字。两个序列中的数字都在long int范围内。
解题思路:
用vetcor将两个序列合并后的数字存储下来,再使用sort函数排序即可。注意奇数长度的序列和偶数长度的序列的最中间位置不是同一个位置。
代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
vector<long> number;
for(int i = 1 ; i <= 2 ; i ++){
int N;
scanf("%d",&N);
for(int j = 1 ; j <= N ; j ++)
{
long num;
scanf("%ld",&num);
number.push_back(num);
}
}
sort(number.begin(),number.end());
if(number.size() % 2 != 0)
printf("%ld",number[number.size()/2]);
else
printf("%ld",number[number.size()/2-1]);
return 0;
}