Cod sursa(job #2582152)

Utilizator PetrescuAlexandru Petrescu Petrescu Data 16 martie 2020 14:16:21
Problema Statistici de ordine Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>
#define MAX 3000000 + 5

using namespace std;

int n, k;
int v[MAX];

int quickPartition(int st, int dr)
{
    int i = st - 1, j = dr + 1, pivot = v[rand() % (dr - st + 1) + st];

    while(1)
    {
        do
        {
            i++;
        }while(v[i] < pivot);

        do
        {
            j--;
        }while(v[j] > pivot);

        if(i < j)swap(v[i], v[j]);
        else return j;
    }

    return 0;
}

void quickSort(int st, int dr)
{
    if(st == dr)return;

    int q = quickPartition(st, dr);
    int t = q - st + 1;

    if(q >= k)quickSort(st, q);
    else
    {
        k -= t;
        quickSort(q + 1, dr);
    }
}

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

    ios::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);
    srand(time(NULL));

    fin >> n >> k;

    int ck = k;
    for(int i = 1; i <= n; i++)
        fin >> v[i];

    quickSort(1, n);

    fout << v[ck];

    fin.close();
    fout.close();

    return 0;
}