Cod sursa(job #2621451)

Utilizator nicu_ducalNicu Ducal nicu_ducal Data 30 mai 2020 14:48:26
Problema Statistici de ordine Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
typedef unsigned long long ul;
typedef long long ll;
using namespace std;

ll n, k;

int quickselect(vector<ll> &v, int k, int lo, int hi){
    if (lo == hi)
        return v[lo];
    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
    uniform_int_distribution<int> distribution(lo, hi);
    // Partitionare
    int piv = distribution(rng);
    swap(v[piv], v[hi]);
    int i = lo - 1;
    for (int j = lo; j < hi; j++){
        if (v[j] <= v[hi]){
            ++i;
            swap(v[i], v[j]);
        }
    }
    swap(v[i + 1], v[hi]);
    int q = i + 1;
    int idx = q - lo + 1;
    if (k == idx)
        return v[q];
    else if (k < idx)
        return quickselect(v, k, lo, q - 1);
    else
        return quickselect(v, k - idx, q + 1, hi);
}

int main(){
    ios_base::sync_with_stdio(0); cin.tie(); cout.tie();
    ifstream cin("sdo.in");
    ofstream cout("sdo.out");

    cin >> n >> k;
    vector <ll> a(n, 0);
    for (ll i = 0; i < n; i++)
        cin >> a[i];

    cout << quickselect(a, k, 0, n - 1);
    //nth_element(a.begin(), a.begin() + k - 1, a.end());
    //cout << a[k - 1];
    return 0;
}