Cod sursa(job #3168296)

Utilizator stefanpiturStefan Alexandru Pitur stefanpitur Data 11 noiembrie 2023 22:25:46
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>

using namespace std;

const int NMAX = 3 * 1e6;
int v[NMAX];

int kth_element(int leftIndex, int rightIndex, int k) {
    if (leftIndex == rightIndex)
        return v[leftIndex];
    
    int pivotIndex = (leftIndex + rightIndex) / 2;
    int pivot = v[pivotIndex];

    int smallerIndex = leftIndex - 1, greaterIndex = rightIndex + 1;

    while (smallerIndex < greaterIndex) {
        do {
            smallerIndex++;
        }
        while (v[smallerIndex] < pivot);

        do {
            greaterIndex--;
        }
        while (v[greaterIndex] > pivot);

        if (smallerIndex < greaterIndex) {
            int aux = v[smallerIndex];
            v[smallerIndex] = v[greaterIndex];
            v[greaterIndex] = aux;
        }
    }

    int smaller = (greaterIndex - leftIndex + 1);

    if (smaller >= k)
        return kth_element(leftIndex, greaterIndex, k);
    return kth_element(greaterIndex + 1, rightIndex, k - smaller);
}

int main()
{
    FILE *fin, *fout;
    fin = fopen("sdo.in", "r");
    fout = fopen("sdo.out", "w");

    int n, k, ans;
    fscanf(fin, "%d %d", &n, &k);
    for (int i = 0; i < n; i++)
        fscanf(fin, "%d", &v[i]);
    
    ans = kth_element(0, n - 1, k);

    fprintf(fout, "%d\n", ans);

    fclose(fin);
    fclose(fout);
    return 0;
}