Cod sursa(job #2294128)

Utilizator dragos99Homner Dragos dragos99 Data 1 decembrie 2018 22:21:28
Problema Statistici de ordine Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include<fstream>
#include<vector>
#include<iostream>
#include<stdlib.h>
#include<stdio.h>

using namespace std;

int n;
int heap[500001];
int length = 0;

inline int father(int x){
    return x>>1;
}

inline int left_son(int x){
    return x<<1;
}

inline int right_son(int x){
    return (x<<1)+1;
}

void heap_up(int x){
    int val = heap[x];

    while( x > 1 && val < heap[father(x)]){
        swap(heap[x], heap[father(x)]);
        x = father(x);
    }
}

void heap_down(int x){
    int son = 1;
    while(son){
        son = 0;
        if(left_son(x) <= length){
            son = left_son(x);
            if(right_son(x) <= length && heap[right_son(x)] < heap[left_son(x)]){
                son = right_son(x);
            }

            if(heap[son] >= heap[x])
                son = 0;
        }

        if(son){
            swap(heap[son], heap[x]);

            x = son;
        }

    }
}

int main()
{

freopen("sdo.in", "r", stdin);
freopen("sdo.out", "w", stdout);

int operatie;
int x, k = 0;

scanf("%d%d", &n, &k);

for(int i = 1 ; i <= n ; i++){
    scanf("%d", &x);
    heap[i] = x;
}

length = n;

for(int i = n / 2 ; i >= 1 ; i--)
    heap_down(i);

for(int i = n ; i >= n - k + 1; i--){
    x = heap[1];
    swap(heap[1], heap[length]);
    length --;
    heap_down(1);
}

printf("%d", x);

return 0;
}