Cod sursa(job #1077825)

Utilizator dm1sevenDan Marius dm1seven Data 11 ianuarie 2014 18:13:02
Problema Statistici de ordine Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <algorithm>
using namespace std;

int quick_partition(int* a, int left, int right, int pivot_id)
{
	//choose a pivot
	int pivot_val = a[pivot_id];

	//move the pivot to the end
	swap(a[pivot_id], a[right]);
	//move the elements <= pivot_val to the left and the others to the right
	int storeIndex = left;
	for (int i = left; i <= right - 1; i++) {
		if (a[i] <= pivot_val) swap(a[i], a[storeIndex++]);
	}
	//finally, swap the element at the position storeIndex with the pivot element, 
	// in this moment positioned at the end of the queue
	swap(a[storeIndex], a[right]);
	
	return storeIndex;
}

//int e_041_sdo_quicksort()
int main()
{
	string in_file = "sdo.in";
	string out_file = "sdo.out";

	int N, K;
	const int MAX_N = 2900000;
	int a[MAX_N];
	ifstream ifs(in_file);
	ifs >> N >> K;
	for (int i = 1; i <= N; i++) ifs >> a[i];
	ifs.close();

	int left = 1, right = N;
	int elements_less = 0; //how many elements are in the left of the indices given by the partition function
	while (elements_less != K) {
		int pivot_id = (left + right) / 2;
		int middle_id = quick_partition(a, left, right, pivot_id);
		if (elements_less + middle_id - left + 1 <= K) {
			elements_less += middle_id - left + 1;
			left = middle_id + 1; 
		}
		else if (elements_less + middle_id - left + 1 > K) right = middle_id - 1;
	}
	a[0] = a[1];//prevention for the case left == 1;
	ofstream ofs(out_file);
	ofs << a[left - 1];
	ofs.close();

	return 0;
}