Cod sursa(job #1746933)

Utilizator liviu23Liviu Andrei liviu23 Data 24 august 2016 10:49:15
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.74 kb
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>

using namespace std;

int a[3000005],n;

int divide(int l,int r) {
    swap(a[r],a[l+rand()%(r-l)]);
    int p=l-1;
    for(int i=l;i<r;i++) {
        if(a[i]<a[r])
            p++,swap(a[p],a[i]);
    }
    swap(a[r],a[p+1]);
    return p+1;
}

void select(int l,int r,int k) {
    if(l==r)
        return;
    int p=divide(l,r);
    int t=p-l+1;
    if(t>=k)
        select(l,p,k);
    else
        select(p+1,r,k-t);
}

int main()
{
    ifstream fin("sdo.in");
    ofstream fout("sdo.out");
    int k;
    fin>>n>>k;
    for(int i=1;i<=n;i++)
        fin>>a[i];
    srand(time(NULL));
    select(1,n,k);
    fout<<a[k];
    return 0;
}