Cod sursa(job #1584031)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 29 ianuarie 2016 17:38:25
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
#define Nmax 3666013
#define DIM 666013
using namespace std;
int N,K;
int A[Nmax];
char buffer[DIM];
int pz = DIM - 1;


void Read(int &A)
{
    A = 0;
    while('0' > buffer[pz] || buffer[pz] > '9')
        if(++pz == DIM)
            fread(buffer,1,DIM,stdin),pz = 0;
    while('0' <= buffer[pz] && buffer[pz] <= '9')
    {
        A = A * 10 + buffer[pz] - 48;
        if(++pz == DIM)
            fread(buffer,1,DIM,stdin),pz = 0;
    }
}

void Read()
{
    Read(N),Read(K);
    int x;
    for(int i = 1; i <= N; ++i)
        Read(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;
}