堆排序&&模拟堆排序

838. 堆排序

输入一个长度为n的整数数列,从小到大输出前m小的数。

输入格式

第一行包含整数n和m。

第二行包含n个整数,表示整数数列。

输出格式

共一行,包含m个整数,表示整数数列中前m小的数。

数据范围

1≤m≤n≤1051≤m≤n≤105,
1≤数列中元素≤1091≤数列中元素≤109

输入样例:

5 3
4 5 1 3 2

输出样例:

1 2 3
#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;

int n,a[300010],m,size;

void down(int x){
 int t=x;
 if(x*2<size&&a[x*2]<a[t]) t=2*x;
 if(x*2+1<size&&a[x*2+1]<a[t]) t=x*2+1;
 if(x!=t){
 swap(a[x],a[t]);
 down(t);}
}


int main(){
 scanf("%d%d",&n,&m);
 size=n;
 for(int i=1;i<=n;i++)  scanf("%d",&a[i]);
 for(int i=n/2;i;i--) down(i);
 while(m--){
    printf("%d ",a[1]);
    a[1]=a[size];
    size--;
    down(1);
 }
 return 0;
}
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

const int N = 1e5 + 10;
int hp[N], ph[N];
int h[N];
int size;

// “I x”,插入一个数x;
// “PM”,输出当前集合中的最小值;
// “DM”,删除当前集合中的最小值(当最小值不唯一时,删除最早插入的最小值);
// “D k”,删除第k个插入的数;
// “C k x”,修改第k个插入的数,将其变为x;

void heap_swap(int u, int v)
{
    swap(ph[hp[u]], ph[hp[v]]);
    swap(hp[u], hp[v]);
    swap(h[u], h[v]);
}

void down(int u)
{
    int t = u;
    if (2*u <= size && h[2*u] < h[t]) t = 2*u;
    if (2*u+1 <= size && h[2*u+1] < h[t]) t = 2*u+1;
    if (t != u)
    {
        heap_swap(t, u);
        down(t);
    }
}

void up(int u)
{
    while (u/2 && h[u] < h[u/2])
    {
        heap_swap(u, u/2);
        u >>= 1;
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    char op[3];
    int a, b;
    int m = 0;
    while (n--)
    {
        scanf("%s", op);
        if (!strcmp(op, "I")) //插入
        {
            scanf("%d", &a);
            m++;
            h[++size] = a, ph[m] = size, hp[size] = m;//ph存储第k个数所在的位置,hp存储在该位置上的数的k值
            up(size);
        }
        else if (!strcmp(op, "PM")) printf("%d\n", h[1]);
        else if (!strcmp(op, "DM")) 
        {
            heap_swap(1, size);
            size--;
            down(1);
        }
        else if (!strcmp(op, "D")) 
        {
            scanf("%d", &a);
            int u = ph[a];
            heap_swap(u, size);
            size--;
            up(u), down(u);
        }
        else
        {
            scanf("%d%d", &a, &b);
            int u = ph[a];
            h[u] = b;
            up(u), down(u);
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值