Cod sursa(job #806587)

Utilizator alex_unixPetenchea Alexandru alex_unix Data 3 noiembrie 2012 00:36:48
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb

#include <fstream>
#include <cstdlib>
#include <ctime>

const int MAX_SIZE(3000001);

int v [MAX_SIZE];
int n, k;

inline void read (void)
{
	std::ifstream input("sdo.in");
	input >> n >> k;
	for (int *iterator(v + 1), *end(v + n) ; iterator <= end ; ++iterator)
		input >> *iterator;
	input.close();
}

inline void print (void)
{
	std::ofstream output("sdo.out");
	output << v[k] << '\n';
	output.close();
}

int partition (int left, int right)
{
	int pivot(v[left + rand() % (right - left + 1)]), i(left - 1), j(right + 1), temp;
	while (true)
	{
		++i;
		while (v[i] < pivot)
			++i;
		--j;
		while (v[j] > pivot)
			--j;
		if (i < j)
		{
			temp = v[i];
			v[i] = v[j];
			v[j] = temp;
		}
		else
			break;
	}
	return j;
}

void order_statistic (int left, int right, int k)
{
	if (left == right)
		return;
	int pivot_index(partition(left,right)), t(pivot_index - left  + 1);
	if (t >= k)
		order_statistic(left,pivot_index,k);
	else
		order_statistic(pivot_index + 1,right,k - t);
}

int main (void)
{
	std::srand(std::time(0));
	read();
	order_statistic(1,n,k);
	print();
	return 0;
}