Cod sursa(job #1259769)

Utilizator avram_florinavram florin constantin avram_florin Data 10 noiembrie 2014 16:11:56
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstring>
#include <cstdlib>

using namespace std;

int partition(vector<int>& values, int left, int right) {
	int poz = left + (rand() % (right - left + 1));
	
	swap(values[poz], values[right]);
	poz = right;
	for (int i = left; i < poz; ++i)
		if (values[i] > values[poz]) {
			swap(values[i], values[poz-1]);
			swap(values[poz], values[poz-1]);
			poz--;
			i--;
		}
	return poz;
}

void find_kth(vector<int>& values, int left, int right, int k) {
	if (right - left >= 1) {
		int poz = partition(values, left, right);
		int t = poz - left + 1;
		if (t >= k)
			find_kth(values, left, poz, k);
		else
			find_kth(values, poz+1, right, k-t);
	}
}
int main() {
	srand(time(NULL));
	ifstream fin("sdo.in");
	ofstream fout("sdo.out");

	int N, K, x;
	vector<int> values;

	fin >> N >> K;
	for (int i = 0; i < N; ++i) {
		fin >> x;
		values.push_back(x);
	}

	find_kth(values, 0, values.size()-1, K);
	fout << values[K-1] << '\n';

	fin.close();
	fout.close();
	return 0;
}