Pagini recente » Cod sursa (job #215015) | Cod sursa (job #1014754) | Cod sursa (job #1129353) | Cod sursa (job #2325709) | Cod sursa (job #1262337)
#include <cstdio>
#include <ctime>
#include <algorithm>
#include <cstdlib>
#define Nmax 3000005
using namespace std;
int a[Nmax],n;
inline int Pivot(int st, int dr)
{
int i=st,j=dr;
while(i<=j)
{
while(i<=j && a[i]<=a[st]) ++i;
while(i<=j && a[j]>=a[st]) --j;
if(i<j)
{
swap(a[i],a[j]);
++i; --j;
}
}
swap(a[i-1],a[st]);
return i-1;
}
inline int Kth_element(int st, int dr, int k)
{
if(st==dr) return a[st];
int piv=st+rand()%(dr-st),poz;
swap(a[st],a[piv]);
poz=Pivot(st,dr);
if(k==poz) return a[poz];
if(k<poz)
return Kth_element(st,poz-1,k);
return Kth_element(poz+1,dr,k);
}
int main()
{
int i,k;
freopen ("sdo.in","r",stdin);
freopen ("sdo.out","w",stdout);
srand(time(0));
scanf("%d%d", &n,&k);
for(i=1;i<=n;++i)
scanf("%d", &a[i]);
printf("%d\n", Kth_element(1,n,k));
return 0;
}