smatskevich

KStatWithStandardPartition

Dec 19th, 2020
467
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. int KStat(std::vector<int>& v, int k) {
  6.   int l = 0, r = v.size();
  7.   while (true) {
  8.     std::swap(v[(l + r) / 2], v[r - 1]);
  9.     const int& x = v[r - 1];
  10.     const auto i = std::partition(v.begin() + l, v.begin() + r - 1, [&x](const int& e) -> bool {
  11.       return e < x;
  12.     });
  13.     std::swap(*i, v[r - 1]);
  14.     const int p = i - v.begin();
  15.     if (p == k) return v[k];
  16.     if (p > k) {
  17.       r = p;
  18.     } else {
  19.       l = p + 1;
  20.     }
  21.   }
  22. }
  23.  
  24. int main() {
  25.   int n = 0, k = 0;
  26.   std::cin >> n >> k;
  27.   std::vector<int> v(n, 0);
  28.   for (int i = 0; i < n; ++i) {
  29.     std::cin >> v[i];
  30.   }
  31.   std::cout << KStat(v, k);
  32.   return 0;
  33. }
  34.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×