Cod sursa(job #604203)

Utilizator claudiumihailClaudiu Mihail claudiumihail Data 20 iulie 2011 20:29:07
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.88 kb
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <string.h>

void radix_sort(int byte, int n ,unsigned long *src, unsigned long *dest)
{
	unsigned long count[256]={0};
	unsigned long index[256];

	for(int i=0; i<n; ++i)
		count[(src[i]>>(byte<<3))&0xff]++;
		
	index[0] = 0;
	for(int i=1; i<256; ++i)
		index[i]=index[i-1]+count[i-1];

	for(int i=0; i<n; ++i)
		dest[index[(src[i]>>(byte<<3))&0xff]++]=src[i];
}

unsigned long counts[(1<<16)+1];
unsigned long indexes[(1<<16)+1];

unsigned long counts1[(1<<16)+1];

void radix_sort16_0(int byte, int n ,unsigned long *src, unsigned long *dest)
{
	for(int i=0; i<n; ++i)
		counts[(src[i]>>(byte*16))&0xffff]++;

	for(int i=1; i<(1<<16); ++i)
		indexes[i] = indexes[i-1]+counts[i-1];

	for(int i=0; i<n; ++i)
		dest[indexes[(src[i]>>(byte*16))&0xffff]++] = src[i];
}

void radix_sort16_1(int byte, int n ,unsigned long *src, unsigned long *dest)
{
	for(int i=0; i<n; ++i)
		counts1[(src[i]>>(byte*16))&0xffff]++;

	indexes[0] = 0;
	for(int i=1; i<(1<<16); ++i)
		indexes[i] = indexes[i-1]+counts1[i-1];

	for(int i=0; i<n; ++i)
		dest[indexes[(src[i]>>(byte*16))&0xffff]++] = src[i];
}

int partition(
	unsigned long *v,
	const int left,
	const int right,
	const int pivotIndex)
{
	unsigned long aux;
	int i = left, j = right, p = v[pivotIndex];

	while(i<j)
	{
		while(v[i] < p)
			++i;

		while(p < v[j])
			--j;

		if(i <= j)
		{
			aux = v[i];
			v[i] = v[j];
			v[j] = aux;
			
			i++;
			j--;
		}
	}

	return (i+j)/2;
}

void nth_element(
	unsigned long *v,
	const int left,
	const int right,
	const int k)
{
	if (left < right)
	{
		const int pivotIndex = (right+left)/2;//(rand()%(right-left)) + left;//
		const int newPivotIndex = partition(v, left, right, pivotIndex);
		
		if (newPivotIndex == k)
			return;
		
		if (newPivotIndex > k )
			nth_element(v, left, newPivotIndex, k);
		if (newPivotIndex < k )
			nth_element(v, newPivotIndex, right, k);
	}
}

int main()
{
	int n, k;
	unsigned long *a, *b;
	std::fstream fin("sdo.in", std::fstream::in);
	std::fstream fout("sdo.out", std::fstream::out);
	
	fin >> n >> k;
	a=new unsigned long[n+1];
	b=new unsigned long[n+1];
	
	for (int i=0; i<n; ++i)
	{
		fin >> a[i];
	}
	
	nth_element(a, 0, n-1, k-1);

	/*for (int i=0; i<k; ++i)
	{
		std::cout << a[i] << "\n";
	}
	std::cout << std::endl;*/
	
	/*radix_sort(0,n,a,b);
	radix_sort(1,n,b,a);
	radix_sort(2,n,a,b);
	radix_sort(3,n,b,a);*/
	
	//std::cout << a[k-1] << "\n";
	
	//radix_sort16_0(0,n,a,b);
	
	/*for (int i=0; i<n; ++i)
	{
		std::cout << b[i] << "\n";
	}
	std::cout << std::endl;*/
	
	
	//radix_sort16_1(1,n,b,a);
	
	/*for (int i=0; i<n; ++i)
	{
		std::cout << a[i] << "\n";
	}
	std::cout << std::endl;*/
	
	//std::cout << a[k-1] << "\n";
	fout << a[k-1];
	
	fin.close();
	fout.close();
	return 0;
}