Cod sursa(job #638849)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 21 noiembrie 2011 19:11:48
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <cstdlib>
#define N 3000010
int A[N];
int n, k;
using namespace std;
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;
}
void computeKthMin(int nth, int l, int r) {
    int u = partition(l, r);
    if(u - l + 1 == nth) {
        return;
    }
    if((u - l + 1) < nth)
      return computeKthMin(nth - (u - l + 1), u + 1, r);
    else
      return computeKthMin(nth, l, u - 1);

}
int main() {
    fin >> n >> k;
    for(int i = 1; i <= n; i++)
      fin >> A[i];
    computeKthMin(k, 1, n);
    fout << A[k];
    return 0;
}