Cod sursa(job #638828)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 21 noiembrie 2011 18:19:49
Problema Statistici de ordine Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <cstdio>
#include <cstdlib>
#define N 3000005
int A[N];
int n, k;
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 < nth)
      return computeKthMin(nth - u, u + 1, r);
    else
      return computeKthMin(nth, l, u - 1);

}
int main() {
    freopen("sdo.in","r",stdin);
    freopen("sdo.out","w",stdout);

    scanf("%d %d",&n,&k);

    for(int i = 1; i <= n; i++)
     scanf("%d",&A[i]);
    printf("%d\n",computeKthMin(k, 1, n));
    return 0;
}