在这里注意一下C++的队列和优先队列返回队首元素的不同方式:
priority_queue<int,vector<int >,less<>> queue1;
queue<int> queue2;
queue2.front();
queue1.top();
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×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.
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
这道题用队列实现,注意在这里引入了哨兵元素,目的是防止数组越界。
#include <iostream>
#include <climits>
#include <queue>
#include <vector>
using namespace std;
int main() {
queue<int> queue1,queue2;
int len1,len2;
cin>>len1;
for (int i = 0; i < len1; ++i) {
int val;
cin>>val;
queue1.push(val);
}
queue1.push(INT_MAX);
cin>>len2;
int cnt=0;
for (int i = 0; i < len2; ++i) {
int val;
cin>>val;
queue2.push(val);
if(cnt==(len1+len2-1)/2){
cout<<min(queue1.front(),queue2.front())<<endl;
return 0;
}
if(queue1.front()<queue2.front()){
queue1.pop();
} else{
queue2.pop();
}
cnt++;
}
queue2.push(INT_MAX);
while (cnt<(len1+len2-1)/2){
if(queue1.front()<queue2.front()){
queue1.pop();
} else{
queue2.pop();
}
cnt++;
}
cout<<min(queue1.front(),queue2.front())<<endl;
return 0;
}