Cod sursa(job #1262337)

Utilizator chiriacandrei25Chiriac Andrei chiriacandrei25 Data 13 noiembrie 2014 08:43:29
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <cstdio>
#include <ctime>
#include <algorithm>
#include <cstdlib>
#define Nmax 3000005

using namespace std;

int a[Nmax],n;

inline int Pivot(int st, int dr)
{
    int i=st,j=dr;
    while(i<=j)
    {
        while(i<=j && a[i]<=a[st]) ++i;
        while(i<=j && a[j]>=a[st]) --j;
        if(i<j)
        {
            swap(a[i],a[j]);
            ++i; --j;
        }
    }
    swap(a[i-1],a[st]);
    return i-1;
}

inline int Kth_element(int st, int dr, int k)
{
    if(st==dr) return a[st];
    int piv=st+rand()%(dr-st),poz;
    swap(a[st],a[piv]);
    poz=Pivot(st,dr);
    if(k==poz) return a[poz];
    if(k<poz)
        return Kth_element(st,poz-1,k);
    return Kth_element(poz+1,dr,k);
}

int main()
{
    int i,k;
    freopen ("sdo.in","r",stdin);
    freopen ("sdo.out","w",stdout);
    srand(time(0));
    scanf("%d%d", &n,&k);
    for(i=1;i<=n;++i)
        scanf("%d", &a[i]);
    printf("%d\n", Kth_element(1,n,k));
    return 0;
}