Cod sursa(job #1584021)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 29 ianuarie 2016 17:31:37
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
#define Nmax 3666013

using namespace std;
int N,K;
int A[Nmax];

void Read()
{
    scanf("%d%d",&N,&K);
    int x;
    for(int i = 1; i <= N; ++i)
        scanf("%d",&A[i]);
    srand(unsigned(time(0)));
}

int Partition(int li, int lf, int piv)
{
    int crt = li;
    swap(A[piv],A[lf]);
    for(int i = li; i < lf; ++i)
        if(A[lf] >= A[i])
            swap(A[i],A[li++]);
    swap(A[li],A[lf]);
    return li;
}

int Nth_element(int li,int lf,int nth)
{
    if(li > lf)
        return li;

    int piv = li + rand()%(lf - li + 1);
    ///piv = lf;
    int pos = Partition(li,lf,piv);

    if(pos == nth)
        return pos;
    if(pos < nth)
        return Nth_element(pos + 1,lf, nth);
    return Nth_element(li,pos - 1,nth);
}

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

    Read();
    printf("%d\n",A[Nth_element(1,N,K)]);

    return 0;
}