我不得不说:这道题真的很水
首先,维护一个大根堆和一个小根堆
大根堆维护数列中小的部分,小根堆维护数列中大的部分
然后,每次输入两个数,大的加入小根堆,小的加入大根堆
为什么?
我不知道
还有一个玄学操作:
把两个堆堆顶判断一下,大根堆堆顶大就叫换堆顶
于是可以愉快的AC了
C++代码(1):
#include<cstdio>
#include<queue>
int n,i,x,y;
using namespace std;
priority_queue<int>largeQ;
priority_queue<int,vector<int>,greater<int> >littleQ;
int main(){
scanf("%d%d",&n,&x);
littleQ.push(x);
printf("%d\n",x);
for (i=0;i<(n-1)/2;++i){
scanf("%d%d",&x,&y);
if (x<y) x^=y^=x^=y;
littleQ.push(x);largeQ.push(y);
int falittle=littleQ.top(),falarge=largeQ.top();
if (falittle<falarge){
littleQ.pop();largeQ.pop();
littleQ.push(falarge);
largeQ.push(falittle);
}
printf("%d\n",littleQ.top());
}
return 0;
}
这个代码中的小根堆永远比大根堆多一个数,相反见C++代码(2):
#include<cstdio>
#include<queue>
int n,i,x,y;
using namespace std;
priority_queue<int>largeQ;
priority_queue<int,vector<int>,greater<int> >littleQ;
int main(){
scanf("%d%d",&n,&x);
largeQ.push(x);
printf("%d\n",x);
for (i=0;i<(n-1)/2;++i){
scanf("%d%d",&x,&y);
if (x<y) x^=y^=x^=y;
littleQ.push(x);largeQ.push(y);
int falittle=littleQ.top(),falarge=largeQ.top();
if (falittle<falarge){
littleQ.pop();largeQ.pop();
littleQ.push(falarge);
largeQ.push(falittle);
}
printf("%d\n",largeQ.top());
}
return 0;
}
转载于:https://www.cnblogs.com/Weakest-konJac/p/10466164.html