Cod sursa(job #2538087)

Utilizator radustn92Radu Stancu radustn92 Data 4 februarie 2020 13:05:26
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
const int NMAX = 3000505;
int N, K;
int nums[NMAX];

int getKthElem(int from, int to, int K) {
	int pivotIdx = (from + to) / 2;
	int pivotValue = nums[pivotIdx];

	int elemsLtePivot = 0;
	for (int idx = from; idx <= to; idx++) {
		if (nums[idx] <= pivotValue) {
			elemsLtePivot++;
		}
	}

	swap(nums[pivotIdx], nums[from + elemsLtePivot - 1]);
	// pivot is on the right position now
	int nextAvailablePosLeft = from;
	for (int idx = from; idx <= to; idx++) {
		if (idx == from + elemsLtePivot - 1) {
			continue;
		}

		if (nums[idx] <= pivotValue) {
			swap(nums[idx], nums[nextAvailablePosLeft]);
			nextAvailablePosLeft++;
		}
	}

	if (K == elemsLtePivot) {
		return pivotValue;
	}
	return K > elemsLtePivot
		? getKthElem(from + elemsLtePivot, to, K - elemsLtePivot)
		: getKthElem(from, from + elemsLtePivot - 2, K);
}

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

	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> N >> K;
	for (int i = 1; i <= N; i++) {
		cin >> nums[i];
	}

	cout << getKthElem(1, N, K) << "\n";
	return 0;
}