Advertisement
Korotkodul

Kst_v1

Oct 2nd, 2023 (edited)
513
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <cmath>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using std::cin;
  6. using std::cout;
  7. using std::max;
  8. using std::min;
  9. using std::string;
  10. using std::vector;
  11.  
  12. void Swap(int* p1, int* p2) {
  13.   int tt = *p1;
  14.   *p1 = *p2;
  15.   *p2 = tt;
  16. }
  17.  
  18. vector<int> ar;
  19.  
  20. void Partition(int low, int high, int xnum) {
  21.   // делим на < и >=
  22.   int lft = low - 1;
  23.   for (int id = low; id <= high; ++id) {
  24.     if (ar[id] < xnum) {
  25.       int* p1 = &ar[id];
  26.       int* p2 = &ar[lft + 1];
  27.       Swap(p1, p2);
  28.       lft++;
  29.     }
  30.   }
  31.   // делим на = и >
  32.   for (int id = lft + 1; id <= high; ++id) {
  33.     if (ar[id] == xnum) {
  34.       int* p1 = &ar[id];
  35.       int* p2 = &ar[lft + 1];
  36.       Swap(p1, p2);
  37.       lft++;
  38.     }
  39.   }
  40. }
  41.  
  42. int Kst(int low, int high, int knum) {
  43.   int piv = ar[low];
  44.   Partition(low, high, piv);
  45.   int lft = low;
  46.   while (ar[lft] != piv) {
  47.     lft++;
  48.   }
  49.   int rgt = high;
  50.   while (ar[rgt] != piv) {
  51.     rgt--;
  52.   }
  53.   // lft - самый левый piv
  54.   // rgt - самый правый piv
  55.   if (knum < lft - low) {
  56.     return Kst(low, lft - 1, knum);
  57.   }
  58.   if (lft - low <= knum <= rgt - low) {
  59.     return piv;
  60.   }
  61.   if (knum > rgt - low) {
  62.     return Kst(rgt + 1, high, knum - (rgt - low + 1));
  63.   }
  64. }
  65.  
  66. int main() {
  67.   std::ios::sync_with_stdio(false);
  68.   std::cin.tie(0);
  69.   std::cout.tie(0);
  70.   int len;
  71.   int knum;
  72.   cin >> len;
  73.   ar.resize(len);
  74.   for (int& el : ar) {
  75.     cin >> el;
  76.   }
  77.   cin >> knum;
  78.   knum--;
  79.   cout << Kst(0, len - 1, knum);
  80. }
  81. /*
  82. 17
  83. 2 2 0 2 1 2 0 2 1 0 2 1 2 2 0 0 2
  84.  
  85. 16
  86. 7 10 3 4 5 11 2 1 2 3 1 5 4 6 7 1
  87. >= 8 - mist
  88. */
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement