Cod sursa(job #3283574)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 9 martie 2025 21:03:36
Problema Statistici de ordine Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#define _CRT_SECURE_NO_WARNINGS // face Visual Studio figuri
#include <bits/stdc++.h>
using namespace std;

class InParser {
private:
	FILE* fin;
	char* buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int& n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		}
		else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long& n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		}
		else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
} fin("sdo.in");
ofstream fout("sdo.out");

mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());

int rand(int min_value, int max_value) {
	return uniform_int_distribution<int>(min_value, max_value)(rng);
}

const int nmax = 3'000'000;
int n, k;
int a[nmax + 5];

int main() {
	fin >> n >> k;
	for (int i = 1; i <= n; ++i) {
		fin >> a[i];
	}
	int kth_element;
	vector<int> subset(n);
	iota(subset.begin(), subset.end(), 1);
	while (true) {
		int pivot = subset[rand(0, subset.size() - 1)];
		vector<int> lessThanPivot, greaterThanPivot;
		for (auto& i : subset) {
			if (i == pivot) {
				continue;
			}
			if (a[i] < a[pivot]) {
				lessThanPivot.emplace_back(i);
			}
			else {
				greaterThanPivot.emplace_back(i);
			}
		}
		if (k <= lessThanPivot.size()) {
			subset = move(lessThanPivot);
		}
		else if (k > lessThanPivot.size() + 1) {
			k -= lessThanPivot.size() + 1;
			subset = move(greaterThanPivot);
		}
		else {
			kth_element = pivot;
			break;
		}
	}
	fout << a[kth_element];
}