Cod sursa(job #3283587)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 9 martie 2025 21:46:17
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.1 kb
#pragma GCC optimize("O3,unroll-loops")
#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 left = 1, right = n, kth_element = -1;
	while (left <= right) {
		if (left == right) {
			kth_element = left;
			break;
		}
		// Folosim algoritmul lui Lomuto de partitionare
		int pivot = rand(left, right); 
		swap(a[pivot], a[right]); // mut elementul pivot la final
		int i = left; // primul element mai mare ca pivotul
		for (int j = left; j < right; ++j) {
			if (a[j] <= a[right]) {
				swap(a[i++], a[j]);
			}
		}
		swap(a[i], a[right]); // acum elementul pivot e pe pozitia i
		if (i < k) {
			left = i + 1;
		}
		else if (i > k) {
			right = i - 1;
		}
		else {
			kth_element = i;
			break;
		}
	}
	assert(kth_element != -1);
	fout << a[kth_element];
}