Cod sursa(job #978934)

Utilizator MtkMarianHagrSnaf MtkMarian Data 30 iulie 2013 15:05:21
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include<cstdio>
#include<cstdlib>

#include<fstream>
#define NMAX 3000005
int A[NMAX], n, k, pivot;

using namespace std;
int RandomizedPartition(int A[NMAX], int limInf, int limSup)
{
	int RandNR = A[limInf + rand()%(limSup- limInf+1)] ;
	int i = limInf -1 ;
	int j = limSup + 1 ;

	while (true )
	{
		do
		{
			++i;
		}
		while(A[i]< RandNR);

		do
		{	
			--j;
		}
		while(A[j]> RandNR);

		if(i < j ) swap(A[i], A[j]);
		else return j;
	}

	return 0;
}


void RandomizedSelect(int A[NMAX],int limInf, int limSup,int k)
{
	if(limInf == limSup) return;

	int q = RandomizedPartition(A,limInf,limSup) ;
	int i = q - limInf + 1; 
	
		if( k <= i )   RandomizedSelect(A, limInf, q  , k );
		else  RandomizedSelect(A, q + 1 , limSup, k-i );
		

}

void citire()
{
	scanf("%d %d",&n,&k);
	for(int i=1; i<=n; ++i)
	{
		scanf("%d",&A[i]);
	}


}


int main()
{
	freopen("sdo.in","r",stdin);
	freopen("sdo.out","w",stdout);

	citire();
	 RandomizedSelect(A,1,n,k);
	printf("%d\n",A[k]);
	return 0 ;
}