Pagini recente » Cod sursa (job #1665856) | Cod sursa (job #947553) | Cod sursa (job #1034369) | Cod sursa (job #1528302) | Cod sursa (job #794629)
Cod sursa(job #794629)
#include <fstream>
#include <stdlib.h>
using namespace std;
int n, k;
int a[3000000];
// Swap two elements in a vector
void swap(int i, int j)
{
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
// Returns the kth element in the vector
int rank(int k, int left, int right)
{
int i = left, j = right;
int pivot = left + (rand() % (right - left));
swap(left, pivot);
pivot = left;
while (i <= j)
{
while (i < j && a[++i] < a[pivot]) ;
while (a[--j] > a[pivot]) ;
if (i < j) swap(i, j);
}
swap(pivot, j);
if (k - 1 < j) return rank(k, left, j);
else if (k - 1 > j) return rank(k, j, right);
else return a[j];
}
int main()
{
ifstream ifs("sdo.in");
ofstream ofs("sdo.out");
ifs >> n >> k;
for (int i = 0; i < n; ++i)
ifs >> a[i];
ofs << rank(k, 0, n) << endl;
ifs.close();
ofs.close();
return 0;
}