Cod sursa(job #2430342)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 14 iunie 2019 12:45:29
Problema Statistici de ordine Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <random>

using namespace std;

ifstream cin("sdo.in");
ofstream cout("sdo.out");

const int nmax = 3e6 + 10;

int n, k;
int a[nmax];

void print_array(int *a, int left, int right) {
    for (int i = left; i <= right; ++i) {
        printf("%d ", a[i]);
    }
    printf("\n");
}

void read_input() {
    cin >> n >> k;
    for (int i = 0; i < n; ++i)
        cin >> a[i];
}

int get_random(int left, int right) {
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(left, right);
    return dis(gen);
}

int partition(int *a, int left, int right) {
    //print_array(a, left, right);
    int pos = left;
    for (int i = left; i < right; ++i) {
        if (a[i] < a[right]) {
            swap(a[pos], a[i]);
            pos += 1;
        }
    }

    swap(a[pos], a[right]);
    //print_array(a, left, right);
    return pos;
}

int randomized_partition(int *a, int left, int right) {
    int pos = get_random(left, right);
    swap(a[pos], a[right]);
    return partition(a, left, right);
}

int randomized_select(int *a, int left, int right, int k) {
    if (left == right)
        return a[left];

    int q = randomized_partition(a, left, right);
    int pivot_position = q - left + 1;

    if (k == pivot_position)
        return a[q];
    if (k < pivot_position)
        return randomized_select(a, left, q - 1, k);
    return randomized_select(a, q + 1, right, k - pivot_position);
}

void solve() {
    int kth_value = randomized_select(a, 0, n - 1, k);
    cout << kth_value << '\n';
}

int main() {
    read_input();
    solve();

    return 0;
}