P1801-黑匣子_NOI导刊2010提高【堆】

正题

题目链接:
https://www.luogu.org/problemnew/show/P1801


大意

有两种操作,
1.将一个数放入黑匣子中
2.++i之后查询第i小的数(初始为i)


解题思路

维护两个堆,一个是比第i小的数大的数的最小堆,一个是比一个是比第i+1小的数小的数的最大堆,插入一个数时,若他比第二个堆的堆顶小就将第二个堆的堆顶放入第一个堆,然后将那个数放入第二个堆,不然就直接放入第一个堆,输出就直接输出第一个堆的堆顶。


代码

#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,num,num2,a[200001],b[200001];
int u[200001],number[200001];
void up1(int x)
{
    while (x>1 && a[x/2]>a[x])
    {
        swap(a[x/2],a[x]);
        x/=2;
    }
}//维护堆1
void down1(int x)
{
    int y;
    while (x*2<=num && a[x*2]<a[x] || x*2+1<=num && a[x*2+1]<a[x])
    {
        y=x*2;
        if (y+1<=num && a[y]>a[y+1]) y++;
        swap(a[y],a[x]);
        x=y;
    }
}//维护堆1
void up2(int x)
{
    while (x>1 && b[x/2]<b[x])
    {
        swap(b[x/2],b[x]);
        x/=2;
    }
}//维护堆2
void down2(int x)
{
    int y;
    while (x*2<=num2 && b[x*2]>b[x] || x*2+1<=num2 && b[x*2+1]>b[x])
    {
        y=x*2;
        if (y+1<=num2 && b[y]<b[y+1]) y++;
        swap(b[y],b[x]);
        x=y;
    }
}//维护堆2
int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++)
        scanf("%d",&number[i]);
    for (int i=1;i<=m;i++)
        scanf("%d",&u[i]);
    for (int i=1,j=1;i<=m;i++)
    {
        for (;j<=u[i];j++)//插入数
        {
            if (number[j]<b[1])
            {
                int z=b[1];
                b[1]=number[j];
                down2(1);
                a[++num]=z;
                up1(num);
            }
            else
            {
                a[++num]=number[j];
                up1(num);
            }
        }
        printf("%d\n",a[1]);//输出
        b[++num2]=a[1];//去掉该数
        up2(num2);
        swap(a[1],a[num]);
        num--;
        down1(1);
    }
}

猜你喜欢

转载自blog.csdn.net/mr_wuyongcong/article/details/80273758