Cod sursa(job #469244)

Utilizator vlad.maneaVlad Manea vlad.manea Data 7 iulie 2010 00:55:17
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <cstdlib>
#include <ctime>
#include <fstream>

using namespace std;

int N, K, A;
int V[3000005];

void read() {

    // input file
    ifstream fin("sdo.in");

    // scan n, k
    fin >> N >> K;

    // scan all
    for (int i = 1; i <= N; ++i) {
        fin >> V[i];
    }

    // close
    fin.close();

}

void swap(int &a, int &b) {

    int aux;
    aux = a; a = b; b = aux;

}

void solve() {

    // set left and right
    int L = 1, R = N;

    // randomize
    srand(time(0));

    // do it
    while (1) {

        // create random
        int r = L + rand() % (R - L + 1);
        int F = V[r], aux, k;

        // iterate smaller than V
        k = 0;
        for (int i = L; i <= R; ++i) {
            if (V[i] < F) {
                swap(V[L + k], V[i]);
                if (V[i] == F) r = i;
                ++k;
            }
        }

        swap(V[L + k], V[r]);

        // where is it?
        if (K < k + L) {

            // is it done?
            if (k == 1) {
                A = V[L];
                break;
            }

            // on the left side
            R = L + k - 1;

        } else if (K <= k + L) {

            // in the center :)
            A = F;
            break;

        } else {

            // is it done?
            if (k == R - L - 1) {
                A = V[R];
                break;
            }

            // on the right
            L = L + k + 1;

        }

    }
  
}

void write() {

    // output file
    ofstream fout("sdo.out");

    // print answer
    fout << A << "\n";

    // close
    fout.close();
    
}

int main() {

    read();

    solve();

    write();
    
    return 0;
    
}