Cod sursa(job #633414)

Utilizator vlad.doruIon Vlad-Doru vlad.doru Data 13 noiembrie 2011 19:07:33
Problema Statistici de ordine Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <cstdio>
#include <algorithm>

using namespace std;

const int N=3000010;
const int MAX=10000;

char buff[MAX];
int pozitie=MAX-1;

int n,k,v[N];

void citire(int &nr){
    nr=0;
    while(buff[pozitie]<'0' || buff[pozitie]>'9')
        if (++pozitie==10005){
            fread (buff,1,10005,stdin);
            pozitie=0;
        }
    while('0'<=buff[pozitie] && buff[pozitie]<='9'){
        nr=nr*10+buff[pozitie]-'0';
        if (++pozitie==10005){
            fread (buff,1,10005,stdin);
            pozitie=0;
        }
     }
}

void read(){
	int i;
	citire(n);
	citire(k);
	for(i=1;i<=n;++i){
		citire(v[i]);
	}
}

inline void schimba(int x,int y){
	v[x]^=v[y];
	v[y]^=v[x];
	v[x]^=v[y];
}

void Partition(int st,int dr){
	int i=st,j=dr,pivot=v[st];
	while(i<j){
		while(v[i]<=pivot && i<=dr && j>i)
			++i;
		while(v[j]>pivot && j>=st && j>=i)
			--j;
		if(j>i)
			schimba(i,j);
	}
	if(j!=st)
		schimba(j,st);
	if(j==k){
		printf("%d",v[j]);
		return;
	}
	if(k<j)
		Partition(st,j-1);
	else{
		Partition(j+1,dr);
	}
}

int main(){
	freopen("sdo.in","r",stdin);
	freopen("sdo.out","w",stdout);
	read();
	Partition(1,n);
	//nth_element(v+1,v+k,v+n+1);
	//printf("%d",v[k]);
	return 0;
}