题解:黑匣子

题目传送门

题意分析

中位数类似,不过这里是给定 \(i\),求第 \(i\) 大。

本文给出对顶堆做法,其余做法请参考中位数。

007

还是这张图

维护一个大根堆 \(x\) 和一个小根堆 \(y\),让 \(x\) 中的元素小于 \(y\) 中的元素,即 \(x.top()<y.top()\)

在我们加入元素 \(p\) 时,先将 \(p\) 加入 \(x\),同时保持 \(x.size()<i\)(否则将 \(x.top()\) 加入 \(y\)),那么答案即 \(y.top()\)

AC 代码

//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
const int N=2e5+1;
int m,n,u,p=1,a[N];
priority_queue<int>x;
priority_queue<int,vector<int>,greater<int> >y;
int main(){
	/*freopen("test.in","r",stdin);
	freopen("test.out","w",stdout);*/
	
	scanf("%d %d",&m,&n);
	for(int i=1;i<=m;i++)scanf("%d",a+i);
	for(int i=1;i<=n;i++){
		scanf("%d",&u);
		for(;p<=u;p++){
			x.push(a[p]);
			if(x.size()==i){
				y.push(x.top());
				x.pop();
			}
		}printf("%d\n",y.top());
		x.push(y.top());
		y.pop();
	}
	
	/*fclose(stdin);
	fclose(stdout);*/
	return 0;
}
posted @ 2025-07-20 17:19  TH911  阅读(5)  评论(0)    收藏  举报