堆的初始化,以及排序

##堆的初始化,以及排序

//无映射关系的堆
#include<bits/stdc++.h>
using  namespace std;
const int N = 1e5 + 10;
int a[N];
int cnt ;
void down(int x)
{
    int t = x;
    if ((2*x) <= cnt && a[2*x] < a[t]) t = 2 * x;
    if ((2 * x + 1) <= cnt && a[2 * x + 1] < a[t]) t = 2 * x + 1;//比较与左右儿子的大小
    if (t != x)
    {
        swap (a[x],a[t]);
        down(t);
    }
}
int main()
{
    int n,m;
    cin>>n>>m;
    for (int i = 1 ; i <= n ; i ++) cin>>a[i];
    cnt = n;
    for (int i = n/2 ; i ; i --) down(i);//初始化堆

    while (m --)
    {
        cout<<a[1]<<" ";
        a[1] = a[cnt];
        cnt --;
        down(1);
    }//输出最小的元素,并每次都删除,因为用一维数组来储存,删除第一个元素不方便,所以把a[1] = a[cnt] ,再进行down()操作
    return 0;
}
//有映射关系的堆
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int a[N] , ph[N] ,hp[N];
int m ,cnt;
void head_swap(int x , int y) // x ,y 是堆数组的下标
{
//交换值以及映射关系
    swap(ph[hp[x]],ph[hp[y]]);
    swap(hp[y],hp[x]);
    swap(a[x], a[y]);//ph[k] = i 表示 第k 个插入的元素在数组中对应的下标是i
    //hp[i] = k 表示下表是i 的元素是k个插入的
}
void down(int x)
{
    int t = x;
    if (2*x < cnt && a[2*x] < a[t]) t = 2 * x;
    if (2 * x + 1 < cnt && a[2 * x + 1] < a[t]) t = 2 * x + 1;
    if (t != x)
    {
        head_swap(t,x);
        down(t);
    }
}
void up (int x)
{
    while (x / 2 && a[x] < a[x / 2])
    {
        head_swap(x , x/2);
        x /= 2;
    }
}
int main()
{
    int n;
    cin>>n;
    while (n --)
    {
        int k,x;
        string op;
        cin>>op;
        if (op == "PM") cout<<a[1];
        else if (op == "I")
        {
            cin>>x;
            cnt ++;
            m ++;
            ph[m] = cnt , hp[cnt] = m;
            a[cnt] = x;
            up(cnt);
        }
        else if (op == "DM")
        {
            head_swap(1,cnt);
            cnt --;
            down(1);
        }
        else if (op == "D")
        {
            cin>>k;
            k = ph[k];
            head_swap(k,cnt);
            cnt --;
            up(k);
            down(k);
        }
        else
        {
            cin>>k>>x;
            k = ph[k];
            a[k] = x;
            down(k);
            up(x);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

觅你风川间!!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值