Cod sursa(job #2092732)

Utilizator shantih1Alex S Hill shantih1 Data 22 decembrie 2017 10:57:34
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>

using namespace std;
ifstream fin("sdo.in");
ofstream fout("sdo.out");

int n, i, j, v[3000005], k, ax, x, st, dr;

int part (int s, int d)
{
	int pv = rand()%(d-s+1)+s, wa=s;
	ax = v[pv];	v[pv] = v[d];	v[d] = ax;
	for (int i = s; i < d; i++)
		if (v[i] <= v[d])
		{
			ax = v[i];	v[i] = v[wa];	v[wa] = ax;
			wa++;
		}
	ax = v[d];	v[d] = v[wa];	v[wa] = ax;
	return wa;
}

int main () {
	
	fin >> n >> k;
	for (i = 1; i <= n; i++)
		fin >> v[i];
	
	srand(unsigned(time(0)));
	
	int rez = 0, y = 0;
	st = 1;	dr = n;
	while (st <= dr && rez == 0)
	{
		x = part(st, dr);
		if (x == k)	
		{
			rez = v[x];
			y = x;
		}
		if (x > k)		dr = x-1;
		if (x < k)		st = x+1;
	}
	
	fout << rez << "\n";
}