堆排序&&模擬堆排序

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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章