Cod sursa(job #2919044)

Utilizator flibiaVisanu Cristian flibia Data 14 august 2022 22:07:46
Problema Statistici de ordine Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>

using namespace std;
 
#ifdef LOCAL
#include "debug.h"
#else
#define dbg(...) 69
#define nl(...) 42
#endif

#define ll long long
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll random(ll st, ll dr) {
    assert(st <= dr);
    return st + rng() % (dr - st + 1);
}

const int MOD = 1e9 + 7;
const int N = 3e6 + 10;

int n, k;
int a[N];

int kth(int l, int r, int k) {
    if (l == r) {
        return a[l];
    }

    int id = random(l, r);
    int nr = 0;
    int tp = r;
    int target = a[id];

    for (int i = l; i <= tp; i++) {
        if (a[i] <= target) {
            nr++;
        } else {
            swap(a[i--], a[tp--]);
        }
    }

    if (nr >= k) {
        return kth(l, l + nr - 1, k);
    }
    return kth(l + nr, r, k - nr);
}

void solve(int test, istream &cin, ostream &cout) {
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }

    cout << kth(1, n, k);
}

int main() {
    ifstream cin("sdo.in");
    ofstream cout("sdo.out");
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    auto start = std::chrono::high_resolution_clock::now();

    bool multiTest = false;

    int t;    
    if (multiTest) {
        cin >> t;
    } else {
        t = 1;
    }

    for (int test = 1; test <= t; test++) {
        solve(test, cin, cout);
    }

    auto stop = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    // cerr << fixed << setprecision(6) << "Running time: " << (double) duration.count() / 1e6 << " seconds" << '\n';

    return 0;
}