Cod sursa(job #2561103)

Utilizator Bulboaca_EugenBulboaca Alexandru Eugen Bulboaca_Eugen Data 28 februarie 2020 16:35:59
Problema Statistici de ordine Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>
using namespace std;
#define zero(x) (x & (-x))
ifstream fin("sdo.in");
ofstream fout("sdo.out");
const int  MAXN = 3 * 1e6 + 3;
int v[MAXN], aux[MAXN], n, k, ans;
int generator(int st, int dr){
    return ((rand() >> 14) + rand()) % (dr - st + 1) + st;
}
void nth_elem(int st, int dr){
    if(dr - st <= 0 ) return;
    int pivot = generator(st, dr), cnt = 0, l = st, copie = 0;
    for(int i = st; i <= dr; ++i){
        if(v[i] <= v[pivot] and i != pivot)
            aux[l++] =  v[i], cnt ++;
    }
    aux[l++] = v[pivot];
    copie = l - 1;
    for(int i = st; i <= dr; ++i)
        if(v[i] > v[pivot]) aux[l++] = v[i];
    if(cnt + 1 == k) ans = pivot;
    else if(cnt > k ) nth_elem(st, copie);
    else if(cnt < k ) nth_elem(copie + 1, dr);
}
int main(){
    fin >> n >> k;
    for(int i = 1; i <= n; ++i){
        fin >> v[i];
    }
    nth_elem(1, n);
    fout << v[ans];
    return 0;
}