Cod sursa(job #1367542)

Utilizator alexandru94hahahalera alexandru94 Data 1 martie 2015 22:34:35
Problema Statistici de ordine Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>


using namespace std;

ifstream in("sdo.in");
ofstream out("sdo.out");

int N, K;
int M[3000000];


void show()
{
    for(int i = 1; i <= N; i++)
    {
        cout << M[i] << " ";
    }
    cout << "\n";
}

// partitionam matricea M dupa valoarea refValue incepand cu indexul start
// si returneaza numarul de ordine al pivotului ales la intamplare relativ
// la interval
int random_partition (int start, int stop){
    /*if(start == stop) {
        return 1;
    }*/

  //  int p_idx = rand() % (stop - start);

//    cout << "p_idx " << p_idx << "\n";
 //   swap(M[stop], M[p_idx + start]);

//    cout << pivot << "\n";
//    show();

    int pivot = M[stop];

//    show();

    int i = start - 1, j = start;
    for(; j <= stop - 1; j++)
    {
        if(M[j] <= pivot) {
            i++;
            swap(M[i], M[j]);
        }
    }

//    cout << "S-a iesit din for \n";
//    show();
    swap(M[i + 1], M[stop]);

//    show();

    return (i + 1);
}



// first time start_position will be 1
int randomized_selection(int kth, int start_position, int final_position)
{
    if(start_position >= final_position) {
        return M[start_position];
    }
    //cout << "r-s " << start_position << " " << final_position << " k-th = " << kth << "\n";
    int idx = random_partition(start_position, final_position);

    //cout << "idx = " << idx << "\n\n\n";
    //show();

    int k = idx - start_position + 1;

    if(k == kth) {
        return M[k];
    } else {
        if(k > kth) {
            return randomized_selection(kth, start_position, idx - 1);
        } else {
            return randomized_selection(kth - k, idx + 1, final_position);
        }
    }
}



int main()
{
    srand(time(NULL));


    in >> N;
    in >> K;
    for(int i = 1; i <= N; i++)
    {
        in >> M[i];
    }

   // cout << random_partition(3, N) << "\n\n\n\n r = ";


  //  cout << randomized_selection(4, 1, N) << "\n";

    out << randomized_selection(K, 1, N);

    return 0;
}