Cod sursa(job #965610)

Utilizator Theorytheo .c Theory Data 24 iunie 2013 11:52:26
Problema Statistici de ordine Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include<fstream>

using namespace std;

ifstream fin("sdo.in");
ofstream fout("sdo.out");

const int Nmax = 3000009;

int N; int K; int H[Nmax];

void Read(){

    fin >> N >> K;
    for(int i = 1; i <= K; ++i)
        fin >> H[i];
}

void BuildHeap(){

    for(int i = 1; i <= K; ++i){

        int j = i;

        while((j >> 1) && H[j] > H[j >> 1]){

            swap(H[j], H[j >> 1]);
            j >>= 1;
        }
    }
}

void Percalate(int Pos){

    int NextPos = Pos;

    if( (Pos << 1) <= K && H[Pos << 1] > H[NextPos]) NextPos = (Pos << 1);

    if( (Pos << 1) + 1 <= K && H[ (Pos << 1) + 1] > H[NextPos]) NextPos = (Pos << 1) + 1;

    if(NextPos != Pos){

        swap(H[Pos], H[NextPos]);
        Percalate(NextPos);
    }
}

void DoTheRest(){


    for(int i = 1; i <= N - K; ++i){

        int X; fin >> X;

        if(H[1] > X){
            H[1] = X; Percalate(1);
        }
    }
}

int main(){

    Read (); BuildHeap (); DoTheRest(); fout << H[1];

    return 0;
}