这道题是一道splay裸题,然而身为蒟蒻的我并不会,所以这道题我维护的是一个大根堆与一个小根堆结合起来的类似沙漏的结构。
本题难点在于询问的不是最大最小值,而是第K小值,所以我们想到了维护这样两个堆,上面是一个大小限定为K-1的大根堆,下面是一个小根堆,每次插入/查询操作时,保持前K-1大的始终在大根堆内。
插入/查询函数:
int heap[200005][3],hsize[3];
int m,n,num[200005],temp;
void put(int x,int i){
heap[++hsize[i]][i]=x;
int son=hsize[i],pa=son>>1;
while(pa>=1){
if(i==1){
if(heap[pa][i]>heap[son][i]){
int t=heap[pa][i];heap[pa][i]=heap[son][i];heap[son][i]=t;
son=pa;
pa>>=1;
}else break;
}else {
if(heap[pa][i]<heap[son][i]){
int t=heap[pa][i];heap[pa][i]=heap[son][i];heap[son][i]=t;
son=pa;
pa>>=1;
}else break;
}
}
}
int get(int i){
int rv=heap[1][i];
heap[1][i]=heap[hsize[i]--][i];
int pa=1,son;
while(pa<=(hsize[i]>>1)){
if(i==1) son=heap[pa<<1][i]<heap[pa<<1|1][i]?pa<<1:pa<<1|1;
else son=heap[pa<<1][i]>heap[pa<<1|1][i]?pa<<1:pa<<1|1;
if(i==1){
if(heap[pa][i]>heap[son][i]){
int t=heap[pa][i];heap[pa][i]=heap[son][i];heap[son][i]=t;
pa=son;
}else break;
}else {
if(heap[pa][i]<heap[son][i]){
int t=heap[pa][i];heap[pa][i]=heap[son][i];heap[son][i]=t;
pa=son;
}else break;
}
}
return rv;
}
对整体的插入/查询:
void putt(int x){
put(x,1);
if(x==heap[1][1]){
get(1);
put(x,2);
int t=get(2);
put(t,1);
}
}
int gett(){
temp++;
int rv=get(1);
put(rv,2);
return rv;
}
附:跑得飞快的代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
int read(){
int rv=0,fh=1;
char c=getchar();
while(c<'0'||c>'9'){
if(c=='-') fh=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
rv=(rv<<1)+(rv<<3)+c-'0';
c=getchar();
}
return rv*fh;
}
int heap[200005][3],hsize[3];
int m,n,num[200005],temp;
void put(int x,int i){
heap[++hsize[i]][i]=x;
int son=hsize[i],pa=son>>1;
while(pa>=1){
if(i==1){
if(heap[pa][i]>heap[son][i]){
int t=heap[pa][i];heap[pa][i]=heap[son][i];heap[son][i]=t;
son=pa;
pa>>=1;
}else break;
}else {
if(heap[pa][i]<heap[son][i]){
int t=heap[pa][i];heap[pa][i]=heap[son][i];heap[son][i]=t;
son=pa;
pa>>=1;
}else break;
}
}
}
int get(int i){
int rv=heap[1][i];
heap[1][i]=heap[hsize[i]--][i];
int pa=1,son;
while(pa<=(hsize[i]>>1)){
if(i==1) son=heap[pa<<1][i]<heap[pa<<1|1][i]?pa<<1:pa<<1|1;
else son=heap[pa<<1][i]>heap[pa<<1|1][i]?pa<<1:pa<<1|1;
if(i==1){
if(heap[pa][i]>heap[son][i]){
int t=heap[pa][i];heap[pa][i]=heap[son][i];heap[son][i]=t;
pa=son;
}else break;
}else {
if(heap[pa][i]<heap[son][i]){
int t=heap[pa][i];heap[pa][i]=heap[son][i];heap[son][i]=t;
pa=son;
}else break;
}
}
return rv;
}
void putt(int x){
put(x,1);
if(x==heap[1][1]){
get(1);
put(x,2);
int t=get(2);
put(t,1);
}
}
int gett(){
temp++;
int rv=get(1);
put(rv,2);
return rv;
}
int f[200005];
int main(){
freopen("in.txt","r",stdin);
m=read();n=read();
for(int i=1;i<=m;i++){
num[i]=read();
}
for(int i=1;i<=n;i++){
f[read()]++;
}
for(int i=1;i<=m;i++){
putt(num[i]);
while(f[i]){
printf("%d\n",gett());
f[i]--;
}
}
/*for(int i=1;i<=10000;i++){
put(rand(),2);
}
for(int i=1;i<=10000;i++){
printf("%d ",get(2));
}*/
fclose(stdin);
return 0;
}
时间: 2024-11-09 00:04:10