Pagini recente » Cod sursa (job #512583) | Cod sursa (job #2716877) | Cod sursa (job #2480662) | Cod sursa (job #2530241) | Cod sursa (job #1941174)
#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+right)/2/*+rand()%(right-left+1)*/];
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;
}
/*fout<<pivot<<'-'<<last<<'-'<<left<<'-'<<right<<": ";
for(int i=1; i<=n; ++i) fout<<v[i]<<' ';
fout<<'\n';*/
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;
}