Cod sursa(job #2887062)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 8 aprilie 2022 19:16:28
Problema Statistici de ordine Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 3e6;

int n, k;
int v[MAXN + 2];

int kth(int l, int r, int k, int *arr) {
	if (l == r)
		return arr[l];

	int pivot = l + rand() % max((r - l + 1), 1);
	int pivotVal = arr[pivot];

	swap(arr[r], arr[pivot]);
	pivot = r;

	int st = l, dr = r - 1;

	while (arr[st] < pivotVal) ++ st;
	while (arr[dr] > pivotVal) -- dr;

	while (st < dr) {
		swap(arr[st], arr[dr]);
		while (arr[st] < pivotVal) ++ st;
		while (arr[dr] > pivotVal) -- dr;
	}

	swap(arr[st], arr[pivot]);
	pivot = st;

	if (k == pivot)
		return arr[k];

	if (k < pivot) {
		return kth(l, pivot - 1, k, arr);
	} else {
		return kth(pivot + 1, r, k - pivot - 1, arr);
	}
}



int main() {
	freopen("sdo.in", "r", stdin);
	freopen("sdo.out", "w", stdout);

	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> n >> k;

	for (int i = 0; i < n; ++ i) {
		cin >> v[i];
	}

	// nth_element(v, v + k - 1, v + n);
	// cout << v[k - 1] << '\n';

	// for (int i = 0; i < n; ++ i)
	// 	cout << v[i] << ' ';
	// cout << '\n';
	cout << kth(0, n - 1, k - 1, v) << '\n';


	return 0;
}