Cod sursa(job #526507)

Utilizator icepowdahTudor Didilescu icepowdah Data 28 ianuarie 2011 15:40:17
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;

#define NMAX 3000000

int vect[NMAX];

void interschimbare(int* x, int* y)
{
	int tmp = *x;
	*x = *y;
	*y = tmp;
}

int partition_rand(int p, int r)
{
	int rand_pos = p+(rand() % (r-p+1));
	interschimbare(&vect[p],&vect[rand_pos]);

	int pivot = vect[p];
	int i = p;
	for (int j=i+1;j<=r;j++)
	{
		if (vect[j] <= pivot)
		{
			i++;
			interschimbare(&vect[i],&vect[j]);
		}
	}
	interschimbare(&vect[p],&vect[i]);
	return i;
}

int order_statistics(int p, int r, int searchKey)
{
	if (p==r)
	{
		return vect[p];
	}

	int q = partition_rand(p,r);
	int k = q-p+1;
	if (k == searchKey)
	{
		return vect[q];
	}
	else if (k > searchKey)
	{
		return order_statistics(p,q-1,searchKey);
	}
	else return order_statistics(q+1,r,searchKey-k);
}

int main(void)
{
	int n, searchKey;
	srand((unsigned int)time(0));

	ifstream f("sdo.in");
	ofstream g("sdo.out");

	f >> n;
	f >> searchKey;	
	for (int i=0;i<n;i++)
		f >> vect[i];
	
	g << order_statistics(0,n-1,searchKey);

	return 0;
}