Pagini recente » Cod sursa (job #2192189) | Cod sursa (job #2426579) | Cod sursa (job #1279143) | Cod sursa (job #2494246) | Cod sursa (job #2294129)
#include<fstream>
#include<vector>
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int n;
int heap[3000001];
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;
}