Pagini recente » Diferente pentru problema/gcdseq intre reviziile 5 si 1 | Cod sursa (job #786019) | Borderou de evaluare (job #1399931) | Borderou de evaluare (job #1598278) | Cod sursa (job #3345307)
// 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
}