Cod sursa(job #1935156)

Utilizator dorin31Geman Dorin Andrei dorin31 Data 22 martie 2017 01:25:50
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>

#define maxN 3000003

using namespace std;

ifstream fin("sdo.in");
ofstream fout("sdo.out");

int n,k,v[maxN];

int getKthElement(int left, int right, int k)
{
    if (left==right) return v[left];

    int pivot=v[left+rand()%(right-left+1)];
    int lowp=0, highp=0;
    for (int i=left; i<=right; ++i)
        if (v[i]<pivot)
            ++lowp;
        else if (v[i]>pivot)
            ++highp;
    if (k>=lowp+1 && k<=(right-left+1)-highp) return pivot;

    int pos1=left, pos2=right;
    while (pos1<pos2)
    {
        while (pos1<=right && v[pos1]<pivot) ++pos1;
        while (pos2>=left && v[pos2]>=pivot) --pos2;
        if (pos1<pos2) swap(v[pos1],v[pos2]);
    }

    int last=0;
    for (int i=left; i<=right; ++i)
        if (v[i]==pivot)
    {
        swap(v[i],v[right]);
        break;
    }
    for (int i=left; i<=right; ++i)
        if (v[i]>=pivot)
    {
        last=i;
        break;
    }
    if (last==left) return getKthElement(left,right-1,k-1);
    else if (last-left>=k) return getKthElement(left,last-1,k);
    else return getKthElement(last,right,k+left-last);
}

int main()
{
    srand(time(NULL));
    fin>>n>>k;
    for (int i=1; i<=n; ++i)
        fin>>v[i];
    fout<<getKthElement(1,n,k);
    return 0;
}