Cod sursa(job #2221181)

Utilizator MoldooooooooMoldoveanu Stefan Moldoooooooo Data 13 iulie 2018 13:24:39
Problema Statistici de ordine Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <cstdio>
#include <stdlib.h>
#include <time.h>
using namespace std;
int N, K, i, st, dr, stmax, drmax;
int long List[3000005], aux, p;
int k;
int main()
{
    freopen("sdo.in", "r", stdin);
    freopen("sdo.out", "w", stdout);
    scanf("%d%d", &N, &K);
    for(i=1; i<=N; i++) scanf("%ld", &List[i]);
    st=stmax=1; dr=drmax=N;
    srand(time(NULL));
    while(p!=K){
        if(st>K){
            st=stmax;
            drmax=dr;
        }
        if(dr<K){
            dr=drmax;
            stmax=st;
        }
        p=rand()%(drmax-stmax+1)+stmax;
        k=List[p];
        while(st<dr){
            while(List[st]<k && st<dr)st++;
            while(List[dr]>k && dr>st)dr--;
            if(st<dr){
                aux=List[st];
                List[st]=List[dr];
                List[dr]=aux;
                if(st==p)p=dr;
                else if(dr==p)p=st;
            }
            st++;
            dr--;
        }
        if(st!=dr){st--; dr++;}
        int cp=p;
        while(List[cp]<List[cp-1]){aux=List[cp]; List[cp]=List[cp-1]; List[cp-1]=aux; cp--;}
        while(List[cp]>List[cp+1]){aux=List[cp]; List[cp]=List[cp+1]; List[cp+1]=aux; cp++;}
    }
    printf("%ld", List[K]);
    return 0;
}