Mai intai trebuie sa te autentifici.
Cod sursa(job #794635)
| Utilizator | Data | 6 octombrie 2012 18:27:19 | |
|---|---|---|---|
| Problema | Statistici de ordine | Scor | 20 |
| Compilator | cpp | Status | done |
| Runda | Arhiva educationala | Marime | 0.91 kb |
#include <fstream>
#include <stdlib.h>
using namespace std;
int n, k;
int a[3000001];
// 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 - 1, j = right + 1;
int pivot = left + (rand() % (right - left)) + 1;
swap(left, pivot);
pivot = left;
while (i <= j)
{
while (i < j && a[++i] < a[pivot]) if (i == j) break;
while (a[--j] > a[pivot]) ;
if (i < j) swap(i, j);
}
swap(pivot, j);
if (k < j) return rank(k, left, j - 1);
else if (k > j) return rank(k, j + 1, right);
else return a[j];
}
int main()
{
ifstream ifs("sdo.in");
ofstream ofs("sdo.out");
ifs >> n >> k;
for (int i = 1; i <= n; ++i)
ifs >> a[i];
ofs << rank(k, 0, n) << endl;
ifs.close();
ofs.close();
return 0;
}