黑匣子

版权声明:转载请注明出处 https://blog.csdn.net/qq_41593522/article/details/78985013

题目描述

Black Box是一种原始的数据库。它可以储存一个整数数组,还有一个特别的变量i。最开始的时候Black Box是空的.而i等于0。这个Black Box要处理一串命令。

命令只有两种:

ADD(x):把x元素放进BlackBox;

GET:i加1,然后输出Blackhox中第i小的数。

记住:第i小的数,就是Black Box里的数的按从小到大的顺序排序后的第i个元素。例如:

我们来演示一下一个有11个命令的命令串。(如下图所示)

现在要求找出对于给定的命令串的最好的处理方法。ADD和GET命令分别最多200000个。现在用两个整数数组来表示命令串:

1.A(1),A(2),…A(M):一串将要被放进Black Box的元素。每个数都是绝对值不超过2000000000的整数,M$200000。例如上面的例子就是A=(3,1,一4,2,8,-1000,2)。

2.u(1),u(2),…u(N):表示第u(j)个元素被放进了Black Box里后就出现一个GET命令。例如上面的例子中u=(l,2,6,6)。输入数据不用判错。

输入输出格式

输入格式:

第一行,两个整数,M,N。

第二行,M个整数,表示A(l)

……A(M)。

第三行,N个整数,表示u(l)

…u(N)。

输出格式:

输出Black Box根据命令串所得出的输出串,一个数字一行。

输入输出样例


输入1:
7 4
3 1 -4 2 8 -1000 2
1 2 6 6
 
  
输出1:
 
  
3
3
1
2

源代码

#include<cstdio>


#define maxn 200005


using namespace std;


int n,m,big[maxn],small[maxn];


void swap(int &x,int &y){
int t=x; x=y; y=t;
}


void BigInsert(int x){
int cur=++big[0];

while (cur>1){
if (big[cur/2]<x){
big[cur]=big[cur/2];
cur/=2;
}
else break;
}

big[cur]=x;
}


void BigDel(){
int cur=1; big[1]=big[big[0]--];

while (cur<=big[0]/2){
int temp;
if (cur*2+1>big[0] || big[cur*2+1]<big[cur*2]) temp=cur*2;
else temp=cur*2+1;

if (big[cur]<big[temp]){
swap(big[cur],big[temp]); cur=temp;
}
else break;
}
}


void SmallInsert(int x){
int cur=++small[0];

while (cur>1){
if (small[cur/2]>x){
small[cur]=small[cur/2];
cur/=2;
}
else break;
}

small[cur]=x;
}


void SmallDel(){
int cur=1; small[1]=small[small[0]--];

while (cur<=small[0]/2){
int temp;
if (cur*2+1>small[0] || small[cur*2+1]>small[cur*2]) temp=cur*2;
else temp=cur*2+1;

if (small[cur]>small[temp]){
swap(small[cur],small[temp]); cur=temp;
}
else break;
}
}


int main(){
scanf("%d%d",&n,&m);

int a[maxn],t[maxn];
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
for (int i=1;i<=m;i++) scanf("%d",&t[i]);

int tj=1;
for (int i=1;i<=n;i++){
BigInsert(a[i]);
if (big[0]>=tj) SmallInsert(big[1]),BigDel();
while (t[tj]==i){
printf("%d\n",small[1]);
BigInsert(small[1]); SmallDel();
tj++;
}
}

return 0;
}
//https://www.luogu.org/problemnew/show/1801

思路及注意事项

大根堆表示要取的数的前k-1个数 
小根堆表示其他的数
当前堆顶为下一个输出 

对于ADD: 每进来一个数,先加入大根堆 若大根堆元素数量大于等于当前的k,就将大根堆顶取出加入小根堆 

对于GET: 输出小根堆顶 将小根堆顶取出,放入大根堆

【备注说明】像一棵二叉树,左儿子是大根堆,右儿子是小根堆,根就是当前要GET的数


猜你喜欢

转载自blog.csdn.net/qq_41593522/article/details/78985013