出自:https://blog.csdn.net/queque_heiya/article/details/106185459
完整代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
const int maxa=1e7+10;
using namespace std;
const int N=1e7+10;
int T,n,k,aa[N];
struct FastIO{
FILE *fp;
static const int S=1e7;
typedef long long ll;
int wpos;
char wbuf[S];
FastIO():wpos(0){}
inline int xchar(){
static char buf[S];
static int len=0,pos=0;
if(pos==len)pos=0,len=fread(buf,1,S,stdin);
return buf[pos++];
}
inline int xuint(){
int c=xchar(),x=0;
while(c<=32)c=xchar();
for(;'0'<=c&&c<='9';c=xchar())x=x*10+c-'0';
return x;
}
inline int xint(){
int s=1,c=xchar(),x=0;
while(c<=32)c=xchar();
if(c=='-')s=-1,c=xchar();
for(;'0'<=c&&c<='9';c=xchar())x=x*10+c-'0';
return x*s;
}
inline void xstring(char *s){
int c=xchar();
while(c<=32)c=xchar();
for(;c>32;c=xchar())*s++=c;
*s=0;
}
inline void wchar(int x){
if(wpos==S)fwrite(wbuf,1,S,stdout);
wbuf[wpos++]=x;
}
inline void wint(ll x){
if(x<0)wchar('-'),x=-x;
char s[24];
int n=0;
while(x||!n)s[n++]='0'+x%10,x/=10;
while(n--)wchar(s[n]);
wchar('\n');
}
inline void wstring(const char *s){
while(*s)wchar(*s++);
}
~FastIO(){
if(wpos)fwrite(wbuf,1,wpos,stdout),wpos=0;
}
}io;
void sort(int l, int k, int r){
if(l>=r) return;
swap(aa[l],aa[(l+r)>>1]);
int L=l,R=r-1,x=aa[l];
while(L<R){
while(L<R&&aa[R]>=x)R--;
aa[L]=aa[R];
while(L<R&&aa[L]<=x)L++;
aa[R]=aa[L];
}
aa[L]=x;
int left=L-l+1;
if(left>k)sort(l,k,L);
if(k>left)sort(L+1,k-left,r);
}
int main(){
int T;
T=io.xint();
while(T--){
n=io.xint(),k=io.xint();
for(int i=0;i<n;++i)
aa[i]=io.xint();
sort(0,n+1-k,n);
//nth_element(aa,aa+n-k,aa+n);
io.wint(aa[n-k]);
}
return 0;
}