Cod sursa(job #1744447)

Utilizator whoasdas dasdas who Data 19 august 2016 20:21:59
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#define IA_PROB "sdo"

#include <cassert>
#include <cstdio>
#include <cstring>

#include <iostream>
#include <fstream>

#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>

#include <algorithm>

using namespace std;

static int rand_int(int l, int r) {
	assert(l < r);
	return l + rand() % (r - l);
}

static int get_pivot(int *v, int l, int r) {
	return rand_int(l, r);
}

/** Partitions v as such: [ < )[ >= )
 * This is so that we don't need to move/swap elements that are equal to the pivot
 * @return the index of the common boundary (lt_hi == ge_lo) */
static int partition(int *v, int l, int r, int pivot) {
	int boundary = l;
	for (int i = l; i < r; i++) {
		if (v[i] < pivot) {
			swap(v[i], v[boundary]);
			boundary++;
		}
	}
	return boundary;
}

int kth_element_impl(int *v, int l, int r, int k) {
	assert(l <= k && k < r);
	if (l == r - 1) {
		return v[l];
	}
	swap(v[r - 1], v[get_pivot(v, l, r)]);
	int boundary = partition(v, l, r - 1, v[r - 1]);
	swap(v[r - 1], v[boundary]);

	if (k == boundary) return v[k];
	else if (k < boundary) return kth_element_impl(v, l, boundary, k);
	else /*if (k > boundary)*/ return kth_element_impl(v, boundary + 1, r, k);
}


int kth_element(int *v, int n, int k) {
	srand(time(0));
	return kth_element_impl(v, 0, n, k);
}

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

	int n, k;
    scanf("%d %d", &n, &k);
    assert(k >= 1 && n >= k);

    int *v = (int*)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) {
    	scanf("%d", &v[i]);
    }

    printf("%d ", kth_element(v, n, k - 1));

    return 0;
}