Cod sursa(job #1103968)

Utilizator romircea2010FMI Trifan Mircea Mihai romircea2010 Data 10 februarie 2014 10:55:12
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <algorithm>
#include <ctime>

using namespace std;

const int NMax = 3000010;

int ans;
int n, K;
int a[NMax];

inline void nth(const int st, const int dr, const int k)
{
    if (st == dr)
    {
        ans = a[st];
        return ;
    }
    int poz = (rand() % (dr - st + 1)) + st;
    int i = st, j = dr;
    int x = a[poz];
    while (i <= j)
    {
        while (a[i] < x)
            ++i;
        while (a[j] > x)
            --j;
        if (i <= j)
        {
            swap(a[i], a[j]);
            ++i, --j;
        }
    }
    if (j - st + 1 < k)
        nth(j+1, dr, k - (j-st+1));
    else
        nth(st, j, k);

}

int main()
{
    srand(time(NULL));
    ifstream f ("sdo.in");
    f>>n>>K;
    for (int i = 1; i<=n; ++i)
        f>>a[i];
    f.close();
    nth(1, n, K);
    ofstream g("sdo.out");
    g<<ans<<"\n";
    g.close();
    return 0;
}