Cod sursa(job #2766616)

Utilizator llama27Asd asd llama27 Data 2 august 2021 15:28:58
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
#include <stdlib.h>
#include <time.h>
using namespace std;
ifstream in("sdo.in");
ofstream out("sdo.out");

#define MAX_SIZE 3000000

int A[MAX_SIZE+5];

int rand_partition(int l, int r)
{
    srand (time(NULL));
    int q = rand() % ((r-l)+1) + l;

    swap(A[q], A[r]);

    // qs partitioning
    int key = A[r];
    int i = l-1;

    for(int j = l; j <= r-1; j++)
        if(A[j] <= key)
            swap(A[++i], A[j]);
    swap(A[++i], A[r]);
    return i;
}

int rand_select(int l, int r, int i)
{
    if(l==r)
        return A[l];
    int q = rand_partition(l,r);
    int k = q-l+1;// Number of elements in A[l..q] + the pivot

    if(i==k)
    /**
    if the pivot is the ans.
        we can check this bcs. the partitioning
        sorts items in place in the final array
    */
        return A[q];

    if(i < k)
        rand_select(l, q-1, i);
    else
        rand_select(q+1, r, i-k);
}

int main()
{
    int n, ith;
    in>>n>>ith;
    for(int i = 1; i<=n;i++)
        in>>A[i];
    out<<rand_select(1,n,ith);
}