Advertisement
smatskevich

KStat

Dec 19th, 2020 (edited)
836
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. int partition(std::vector<int>& v, int l, int r) {
  5.   if (r - l <= 1) return l;
  6.   std::swap(v[r - 1], v[(r + l) / 2]);
  7.   int i = l;
  8.   const int& x = v[r - 1];
  9.   for (int j = l; j < r - 1; ++j) {
  10.     if (v[j] < x) {
  11.       std::swap(v[i], v[j]);
  12.       ++i;
  13.     }
  14.   }
  15.   std::swap(v[i], v[r - 1]);
  16.   return i;
  17. }
  18.  
  19. int KStat(std::vector<int>& v, int k) {
  20.   int l = 0, r = v.size();
  21.   while (true) {
  22.     const int p = partition(v, l, r);
  23.     if (p == k) return v[k];
  24.     if (p > k) {
  25.       r = p;
  26.     } else {
  27.       l = p + 1;
  28.     }
  29.   }
  30. }
  31.  
  32. int main() {
  33.   int n = 0, k = 0;
  34.   std::cin >> n >> k;
  35.   std::vector<int> v(n, 0);
  36.   for (int i = 0; i < n; ++i) {
  37.     std::cin >> v[i];
  38.   }
  39.   std::cout << KStat(v, k);
  40.   return 0;
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement