838. Heap Sort + Simulate Heap with Array

Input a sequence of integers of length n, and output the first m numbers in ascending order.

Input format
The first line contains integers n and m.

The second line contains n integers, representing a sequence of integers.

Output Format
One line contains m integers, representing the first m in the integer sequence.

Data range
1≤m≤n≤105,
1≤elements in the sequence≤109
Input sample:
5 3
4 5 1 3 2Output
sample:
1 2 3


#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int h[N], idx;

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

void up(int x)
{
    
    
    while(x / 2 && h[x/2] > h[x]) {
    
    
        swap(h[x], h[x/2]);
        x /= 2;
    }
}

int main()
{
    
    
    int n, m;
    cin >> n >> m;
    int x;
    
    // for(int i=1; i<=n; i++) {
    
    
    //     cin >> x;
    //     h[++idx] = x;
    //     up(idx);
    // }
    
    for(int i=1; i<=n; i++) cin >> h[i];
    idx = n;
    
    for(int i=n/2; i>=0; i--) down(i);
    
    while(m--) {
    
    
        cout << h[1] << " ";
        h[1] = h[idx];
        idx --;
        down(1);
    }
    
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324101783&siteId=291194637