Pagini recente » Cod sursa (job #2277945) | Cod sursa (job #2401466) | Cod sursa (job #1158083) | Cod sursa (job #164628) | Cod sursa (job #2887066)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e6;
int n, k;
int v[MAXN + 2];
int kth(int l, int r, int k, int *arr) {
if (l >= r)
return arr[l];
int pivot = l + rand() % (r - l + 1);
int pivotVal = arr[pivot];
swap(arr[r], arr[pivot]);
pivot = r;
int st = l, dr = r - 1;
while (arr[st] < pivotVal) ++ st;
while (arr[dr] > pivotVal) -- dr;
while (st < dr) {
swap(arr[st], arr[dr]);
while (arr[st] < pivotVal) ++ st;
while (arr[dr] > pivotVal) -- dr;
}
swap(arr[st], arr[pivot]);
pivot = st;
if (k == pivot)
return arr[k];
if (k < pivot) {
return kth(l, pivot - 1, k, arr);
} else {
return kth(pivot + 1, r, k - pivot - 1, arr);
}
}
int main() {
freopen("sdo.in", "r", stdin);
freopen("sdo.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for (int i = 0; i < n; ++ i) {
cin >> v[i];
}
// nth_element(v, v + k - 1, v + n);
// cout << v[k - 1] << '\n';
// for (int i = 0; i < n; ++ i)
// cout << v[i] << ' ';
// cout << '\n';
cout << kth(0, n - 1, k - 1, v) << '\n';
return 0;
}