Cod sursa(job #1262418)

Utilizator dnprxDan Pracsiu dnprx Data 13 noiembrie 2014 10:17:21
Problema Statistici de ordine Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <ctime>
#include <cstdlib>

using namespace std;

int a[3000005], n, k;

void Citire()
{
    ifstream fin ("sdo.in");
    fin >> n >> k;
    for(int i = 1; i <= n; ++i)
        fin >> a[i];
    fin.close();
}

inline void Sch(int &x, int &y)
{
    int aux;
    aux = x;
    x = y;
    y = aux;
}

// returneaza pozitia unde s-a asezat pivotul
int Pivot(int st, int dr)
{
    int i, j, piv;
    piv = a[st];
    i = st + 1;
    j = dr;
    while (i <= j)
    {
        if (a[i] <= piv) i++;
        if (a[j] >= piv) j--;
        if (i < j && a[i] > piv && piv > a[j])
        {
            Sch(a[i], a[j]);
            i++; j--;
        }
    }
    Sch(a[st], a[i-1]);
    return i-1;
}

int KElem(int st, int dr)
{
    int p;
    p = Pivot(st, dr);
    if (p == k) return a[p];
    if (p < k) return KElem(p+1, dr);
    return KElem(st, p-1);
}

void Afisare()
{
    int i;
    i = KElem(1, n);
    ofstream fout ("sdo.out");
    fout << i << "\n";
    fout.close();
}

int main()
{
    Citire();
    Afisare();
    return 0;
}