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.
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×105) 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
给出两个已排序序列,求这两个序列合并后的中间数
其实可以存储两个数组,然后 sort
大法。
但是我一开始想到的是 priority_queue
,那就两种都做一下吧。
priority_queue
取出指定下标的数这边有个坑,就是因为你不能直接取出指定下标的数,所以你只能遍历 s i z e 2 \frac{size}{2} 2size 次,然后取出中位数。
但是奇数和偶数的中位数的取法不一样,奇数是取到 i<=size/2
;偶数是取到 i
在第一份代码里面就是没有区分出来奇数和偶数,所以出错
#include
#include
using namespace std;
priority_queue<int,vector<int>,greater<int> > q;
int main() {
int n,m;
while(!q.empty()) {
q.pop();
}
scanf("%d",&n);
for(int i=0; i<n; i++) {
scanf("%d",&m);
q.push(m);
}
scanf("%d",&n);
for(int i=0; i<n; i++) {
scanf("%d",&m);
q.push(m);
}
int size=q.size();
size=size/2;
while(size){
n=q.top();
q.pop();
size--;
}
n=q.top();
cout<<n;
return 0;
}
#include
#include
using namespace std;
priority_queue<int,vector<int>,greater<int> > q;
int main() {
int n,m;
while(!q.empty()) {
q.pop();
}
scanf("%d",&n);
for(int i=0; i<n; i++) {
scanf("%d",&m);
q.push(m);
}
scanf("%d",&n);
for(int i=0; i<n; i++) {
scanf("%d",&m);
q.push(m);
}
int size=q.size();
if(size%2==0) {
for(int i=0; i<size/2; i++) {
n=q.top();
q.pop();
}
} else {
for(int i=0; i<=size/2; i++) {
n=q.top();
q.pop();
}
}
cout<<n;
return 0;
}
#include
using namespace std;
int a[400005];
int main(){
int n,m;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
for(int i=0;i<m;i++)
scanf("%d",&a[n+i]);
sort(a,a+m+n);
int mid=(m+n-1)/2;
cout<<a[mid]<<endl;
return 0;
}