Cod sursa(job #2625310)

Utilizator raluca1234Tudor Raluca raluca1234 Data 5 iunie 2020 21:08:57
Problema Statistici de ordine Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
// Infoarena - SDO (Statistici de Ordine)
#include <iostream>
#include <fstream>
#include <vector>
#include <random>   //mt19937
	
int partition(std::vector<int>& arr, int left, int right)
{		
    std::mt19937 rnd(time(0));
    std::uniform_int_distribution <int> distribution (left, right);
    int pivot = (distribution(rnd));

    std::swap(arr[right], arr[pivot]);
    int pivot_value = arr[right];

    int pos = left;
    for (int i = left; i < right; ++i) {
        if (arr[i] <= pivot_value) {
            std::swap(arr[pos], arr[i]);
            pos++;
        }
    }
    std::swap(arr[pos], arr[right]);
    // Now the pivot is placed correctly (in the sorted array)
    
    return pos;
}
	
int kthOrderStatistic(std::vector<int>& arr, int left, int right, int k) 
{
    if (k > 0 && k <= right - left + 1) {
        int index = partition(arr, left, right);
	
        if (index - left + 1 == k) {
            return arr[index];
        }
        if (index - left + 1 > k) {  // go to the left
            return kthOrderStatistic(arr, left, index - 1, k);
        }
        // go to the right
        return kthOrderStatistic(arr, index + 1, right, k - (index - left + 1));
    }
    return 0;	
}
	
int main()
{
    std::ifstream fin("sdo.in");
    std::ofstream fout("sdo.out");

    int n, k;
    fin >> n >> k;
	
    std::vector<int> arr;
    for (int i = 0; i < n; ++i) {
        int value;
        fin >> value;
        arr.emplace_back(value);
    }
	
    fout << kthOrderStatistic(arr, 0, n - 1, k);
	
    return 0;
}