Cod sursa(job #2582175)

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

using namespace std;

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, int k)
{
    if(st == dr)return;

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

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

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

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

    int n, k;
    fin >> n >> k;

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

    quickSort(1, n, k);

    fout << v[k];

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

    return 0;
}