Cod sursa(job #1104088)

Utilizator cdt2014Cont de Teste cdt2014 Data 10 februarie 2014 14:16:04
Problema Statistici de ordine Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
using namespace std;

void print(vector<int> V) {
	for (vector<int>::iterator it=V.begin(); it!=V.end(); ++it) 
		cout << *it << " ";
	cout << endl;
}

int Partition(vector<int>& V, int left, int right, int pivot) {
	int high = right;
	int X = V[pivot];
	int i;

	for (i=left; i<high; ) {
		if (V[i] > X) {
			swap(V[i], V[high]);
			high --;
		} else if (V[i] == X) {
			swap(V[i], V[i+1]);
		} else {
			i ++;
		}
	}

	return i;
}

int QuickSelect(vector<int>& V, int target, int left, int right) {
	int pivot = rand() % (right - left + 1) + left;
	int newPivot = Partition(V, left, right, pivot);

	//cout << pivot << " " << newPivot << endl;
	//print(V);

	if (newPivot == target) {
		return V[target];
	} else if (newPivot < target) {
		return QuickSelect(V, target, newPivot + 1, right);
	} else {
		return QuickSelect(V, target, left, newPivot-1);
	}
}

int main() {
	srand(time(0));

	ifstream in("sdo.in");
	ofstream out("sdo.out");
	int N, K;
	vector<int> V;

	in >> N >> K;
	while (N--) { 
		int x;
		in >> x;
		V.push_back(x);
	}

	out << QuickSelect(V, K - 1, 0, V.size() - 1) << "\n";
	return 0;
}