Cod sursa(job #1474494)

Utilizator pepsiM4A1Ozturk Arif pepsiM4A1 Data 22 august 2015 02:17:35
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <cstdio>
#include <algorithm>
#define DIM 10000
using namespace std;
int a[3000006],n,k;
char buff[DIM];
int poz=0;
void next()
{
    ++poz;
    if(poz>=DIM)
    {
        poz=0;
        fread(buff,1,DIM,stdin);
    }
}
int citeste()
{
    char semn='+';
    while((buff[poz]!='-')&&(!('0'<=buff[poz]&&buff[poz]<='9')))
    {
        next();
    }
    if(buff[poz]=='-')
    {
        semn='-';
        next();
    }
    int nr=0;
    while('0'<=buff[poz]&&buff[poz]<='9')
    {
        nr*=10;
        nr+=(buff[poz]-'0');
        next();
    }
    if(semn=='-') nr*=(-1);
    return nr;
}
int part(int s,int e)
{
    int p=a[s],i=s-1,j=e+1;
    while(1)
    {
        do
        {
            i++;
        }while(a[i]<p&&i<=e);
        do
        {
            j--;
        }while(a[j]>p&&j>=s);
        if(i<j) swap(a[i],a[j]);
        else return j;
    }
    return 0;
}
void sdo(int s,int e,int k)
{
    if(s>=e) return;
    int p=part(s,e),p2;
    p2=p-s+1;
    if(p2>=k) sdo(s,p,k);
    else sdo(p+1,e,k-p2);
}
int main()
{
    freopen ("sdo.in","r",stdin);
    freopen ("sdo.out","w",stdout);
    n=citeste();
    k=citeste();
    for(int i=1;i<=n;i++) a[i]=citeste();
    random_shuffle(a+1,a+n+1);
    sdo(1,n,k);
    printf("%d\n",a[k]);
}