Cod sursa(job #2538082)

Utilizator radustn92Radu Stancu radustn92 Data 4 februarie 2020 12:55:54
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <cstdio>
#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 + rand() % (to - from + 1);
	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);

	scanf("%d%d", &N, &K);
	for (int i = 1; i <= N; i++) {
		scanf("%d", &nums[i]);
	}

	srand(time(0));
	printf("%d\n", getKthElem(1, N, K));
	return 0;
}