Cod sursa(job #2624351)

Utilizator roxana1708Roxana Gherghina roxana1708 Data 4 iunie 2020 18:57:51
Problema Statistici de ordine Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#include <stdlib.h>

using namespace std;

#define maxn 3000001
int n, k, i, j, ind_pivot;
long long int v[maxn], pivot;

void swap(long long int *x, long long int *y){
    int temp = *x;
    *x = *y;
    *y = temp;
}

long long int partition(int l, int r){

    pivot = v[l + (rand() % (r - l))];

    i = l; j = r;

    while(i <= j) {
        while(v[i] < pivot)
            i++;
        while(v[j] > pivot)
            j--;
        if(i <= j) {
            swap(&v[i], &v[j]);
            i++;
            j--;
        }
    }

    return i;
}

long long int quickSelect(int st, int dr, int index){
    ind_pivot = partition(st, dr);

    if(ind_pivot - st == index-1)
        return v[ind_pivot];

    if(ind_pivot - st > index-1)
        return quickSelect(st, ind_pivot - 1, index);

    return quickSelect(ind_pivot + 1, dr, index - ind_pivot + st - 1);

}

int main() {
    ifstream f("sdo.in");
    ofstream g("sdo.out");

    f >> n >> k;

    for(i = 0; i < n; i++)
        f >> v[i];

    quickSelect(0, n-1, k);

    g << v[k];
    return 0;
}