Cod sursa(job #3345307)

Utilizator nstefanNeagu Stefan nstefan Data 9 martie 2026 01:35:34
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
// https://www.infoarena.ro/job_detail/3345121?action=view-source
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <random>
using namespace std;

class Solution {
  vector<int> v;
  int k;
  std::mt19937 randomEngine;

  int choosePivotIndex(int left, int right) {
    return std::uniform_int_distribution<int>(left, right - 1)(randomEngine);
  }

  int partition(int left, int right, int pivotIndex) {
    int pivot = v[pivotIndex];
    swap(v[pivotIndex], v[right - 1]);
    int newLocation = right - 2;
    int index = left;
    
    while (index <= newLocation) {
      if (v[newLocation] >= pivot) { // keeps the invariant: v[newLocation] < pivot
        newLocation--;
        continue;
      }
      if (v[index] >= pivot)
        swap(v[index], v[newLocation--]);
      index++;
    }

    swap(v[right - 1], v[index]);
    return index;
  }
public:
  Solution(const vector<int>& v_, int k_) : v{std::move(v_)}, k{k_}, randomEngine{} {}

  int solve(int left = -1, int right = -1) {
    if (left == -1) left = 0;
    if (right == -1) right = v.size();
    if (left >= right) return -1;

    int pivotIndex = choosePivotIndex(left, right);
    pivotIndex = partition(left, right, pivotIndex);
    // std::cout << "(" << v[pivotIndex] << ") "; for (int i = left; i < right; i++) std::cout << v[i] << ' '; std::cout << '\n';

    if (pivotIndex == k - 1)
      return v[k - 1];
    else if (pivotIndex < k - 1)
      return solve(pivotIndex + 1, right);
    else
      return solve(left, pivotIndex);
  }
};


int main() {
// #define LOCAL

#ifndef LOCAL
  std::ifstream fin("sdo.in");
  std::ofstream fout("sdo.out");
  int n, k; fin >> n >> k;
  vector<int> v; v.reserve(n); for (int i = 0; i < n; i++) { int x; fin >> x; v.push_back(x); }
  fout << Solution(v, k).solve();
#else
  std::cout << Solution(
    { 1, 10, 4, 13, 7, 6, 11, 14 },
    3
  ).solve();
#endif
}