Pagini recente » Cod sursa (job #2380540) | Cod sursa (job #2724466) | Cod sursa (job #205504) | Cod sursa (job #1176529) | Cod sursa (job #1941215)
#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;
}