Cod sursa(job #867177)

Utilizator darrenRares Buhai darren Data 29 ianuarie 2013 12:02:14
Problema Statistici de ordine Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <algorithm>

using namespace std;

int N, P;
int A[3000002];

int getelement(int i1, int i2, int pnow)
{
	if (i1 == i2) return A[i1];
	
	int pivot = A[i1];
	int lesp = 0, morp = 0;
	for (int i = i1; i <= i2; ++i)
		if (A[i] < pivot)
			++lesp;
		else if (A[i] > pivot)
			++morp;
	if (pnow >= lesp + 1 && pnow <= (i2 - i1 + 1) - morp) return pivot;
	
	int pos1 = i1, pos2 = i2;
	while (pos1 < pos2)
	{
		while (pos1 <= N && A[pos1] < pivot) ++pos1;
		while (pos2 >= 1 && A[pos2] >= pivot) --pos2;
		
		if (pos1 < pos2) swap(A[pos1], A[pos2]);
	}
	
	int last = 0;
	for (int i = i1; i <= i2; ++i)
		if (A[i] == pivot)
		{
			swap(A[i], A[i2]);
			break;
		}
	for (int i = i1; i <= i2; ++i)
		if (A[i] >= pivot)
		{
			last = i;
			break;
		}
	
	if (last == i1) return getelement(i1, i2 - 1, pnow - 1);
	if (last - i1 >= pnow) return getelement(i1, last - 1, pnow);
	return getelement(last, i2, pnow - (last - i1));
}

int main()
{
	ifstream fin("sdo.in");
	ofstream fout("sdo.out");
	
	fin >> N >> P;
	//++P;
	
	for (int i = 1; i <= N; ++i)
		fin >> A[i];
	
	fout << getelement(1, N, P) << '\n';
}