Cod sursa(job #3347153)

Utilizator aspaAlexandru Valentin Grigorescu aspa Data 15 martie 2026 18:44:23
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
// Quick select implementation, O(n) time complexity, O(n^2) worst case
// Link to pbinfo solution: https://www.pbinfo.ro/detalii-evaluare/63528113
#include <iostream>
#include <bits/stdc++.h>
#include <iostream>

using namespace std;

ifstream fin("sdo.in");
ofstream fout("sdo.out");

unsigned long long int quick_select(vector<unsigned long int> &a, unsigned long int &n, unsigned long int &k, unsigned long int l){
    unsigned long int pivot = l + ( rand() % ( n-l ) );
    swap(a[n-1], a[pivot]);
    pivot = n-1;
    unsigned long int poz = l; 

    for(unsigned long int i=l; i<pivot; i++){
        if(a[i] < a[pivot]){
            swap(a[i], a[poz]);
            poz++;
        }
    }
    swap(a[poz], a[pivot]);
    if(poz == k-1)
        return a[poz];
    else if(poz < k-1)
        return quick_select(a, n, k, poz+1);
    else return quick_select(a, poz, k, l);
    
    return -1;
}

int main(){
    unsigned long int n, val, k;
    fin>>n>>k;
    if(k > n){
        cout<<"K bigger than the number of elements in the array.";
        return 1;
    }
    vector<unsigned long int> a;
    a.reserve(n+1);
    for(unsigned long int i=0; i<n; i++){
        fin>>val;    
        a.push_back(val);
    }
    fout<<quick_select(a, n, k, 0);


    return 0;
}