Cod sursa(job #855545)

Utilizator claudiumihailClaudiu Mihail claudiumihail Data 15 ianuarie 2013 10:17:57
Problema Statistici de ordine Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <iostream>
#include <cstdlib>

#define MAXN 3000001

using namespace std;

unsigned int vec[MAXN];

template<typename T>
void do_partition(T vec[], int& left, int& right, const T& pivotVal)
{
    while (left < right)
    {
        while (vec[left] < pivotVal) ++left;
        while (pivotVal < vec[right]) --right;
        
        if (left < right)
        {
            swap(vec[left], vec[right]);
            ++left;
            --right;
        }
    }
}

template<typename T>
int find_nth_element(T vec[], int left, int right, int n)
{
    int pivotPos = left + (right - left)/2;//(rand() % (right - left + 1));
    int newLeft = left;
    int newRight = right;
    
    do_partition(vec, newLeft, newRight, vec[pivotPos]);
    
    if (n == (newRight + newLeft) / 2)
    {
        return vec[(newRight + newLeft) / 2];
    }
    
    if (n < newRight)
    {
        return find_nth_element(vec, left, newRight, n);
    }
    else
    {
        return find_nth_element(vec, newLeft, right, n);
    }
}

template <typename T>
int nth_element(T vec[], int sizeVec, int n)
{
    return find_nth_element(vec, 0, sizeVec - 1, n);
}

int main()
{
    int n, k;
    
    fstream fin("sdo.in", fstream::in);
    fstream fout("sdo.out", fstream::out);
    
    fin >> n >> k;
    
    for (int i=0; i<n; ++i)
    {
        fin >> vec[i];
        //cout << vec[i] << " ";
    }
    //cout << endl;
    
    fout << nth_element(vec, n, k-1) << endl;
    
    return 0;
}