Pagini recente » Cod sursa (job #58045) | Cod sursa (job #1998754) | Cod sursa (job #2364024) | Cod sursa (job #2102887) | Cod sursa (job #855544)
Cod sursa(job #855544)
#include <fstream>
#include <iostream>
#include <cstdlib>
#define MAXN 3000001
using namespace std;
unsigned int vec[MAXN];
template<typename T>
void do_partition(T vec[], int& left, int& right, const T& pivotVal)
{
while (left < right)
{
while (vec[left] < pivotVal) ++left;
while (pivotVal < vec[right]) --right;
if (left < right)
{
swap(vec[left], vec[right]);
++left;
--right;
}
}
}
template<typename T>
int find_nth_element(T vec[], int left, int right, int n)
{
int pivotPos = left + (rand() % (right - left + 1));
int newLeft = left;
int newRight = right;
do_partition(vec, newLeft, newRight, vec[pivotPos]);
if (n == (newRight + newLeft) / 2)
{
return vec[(newRight + newLeft) / 2];
}
if (n < newRight)
{
return find_nth_element(vec, left, newRight, n);
}
else
{
return find_nth_element(vec, newLeft, right, n);
}
}
template <typename T>
int nth_element(T vec[], int sizeVec, int n)
{
return find_nth_element(vec, 0, sizeVec - 1, n);
}
int main()
{
int n, k;
fstream fin("sdo.in", fstream::in);
fstream fout("sdo.out", fstream::out);
fin >> n >> k;
for (int i=0; i<n; ++i)
{
fin >> vec[i];
//cout << vec[i] << " ";
}
//cout << endl;
fout << nth_element(vec, n, k-1) << endl;
return 0;
}