Cod sursa(job #469238)

Utilizator vlad.maneaVlad Manea vlad.manea Data 7 iulie 2010 00:25:23
Problema Statistici de ordine Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <cstdio>
#include <cstdlib>

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

void read() {

    // input file
    freopen("sdo.in", "r", stdin);

    // scan n, k
    scanf("%d%d", &N, &K);

    // scan all
    for (int i = 1; i <= N; ++i) {
        scanf("%d", &V[i]);
    }

}

void solve() {

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

    // 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) {
                aux = V[L + k];
                V[L + k] = V[i];
                V[i] = aux;
                if (V[i] == F) r = i;
                ++k;
            }
        }

        aux = V[L + k];
        V[L + k] = V[r];
        V[r] = aux;

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

            // 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
    freopen("sdo.out", "w", stdout);

    // print answer
    printf("%d\n", A);
    
}

int main() {

    read();

    solve();

    write();
    
    return 0;
    
}