Cod sursa(job #638850)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 21 noiembrie 2011 19:14:01
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#include <cstdlib>
#define N 3000010

using namespace std;

int A[N];
int n, k;
ifstream fin ("sdo.in");
ofstream fout ("sdo.out");

int swap(int i, int j) {
    int aux = A[i];
    A[i] = A[j];
    A[j] = aux;
}

int partition(int p, int q) {
    int x = rand() % (q - p + 1);
    swap(p, x + p);
    int i = p + 1;
    for(int j = p + 1; j <= q; j++) {
        if(A[j] <= A[p]) {
            swap(j, i);
            i++;
        }
    }
    swap(i - 1, p);
    return i - 1;
}
int computeKthMin(int nth, int l, int r) {
    int u = partition(l, r);
    if(u - l + 1 == nth) {
        return A[u];
    }
    if((u - l + 1) < nth)
      return computeKthMin(nth - (u - l + 1), u + 1, r);
    else
      return computeKthMin(nth, l, u - 1);

}
int main() {
    freopen("sdo.in","r",stdin);
    freopen("sdo.out","w",stdout);
    fin >> n >> k;
    for(int i = 1; i <= n; i++)
      fin >> A[i];
    fout << computeKthMin(k, 1, n);
    return 0;
}