天天看點

HIHO #1128 : 二分·二分查找(快速排序一半)

題目連結

快速排序應用

#include<bits/stdc++.h>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define LL long long
#define pb push_back
#define gcd __gcd

#define For(i,j,k) for(int i=(j);i<k;i++)
#define lowbit(i) (i&(-i))
#define _(x) printf("%d\n",x)

const int maxn = +;
const int inf  =  << ;

LL a[maxn];
LL k;

int kth_sort(int l,int r){
    //printf("l = %d, r = %d\n",l,r);
    if(l>r){
        if(a[l]==k)return l+;
        else return -;
    }
    int low = l,high = r;
    int key = a[l];//select the key
    while(low<high){
        while(low<high&&a[high]>key)high--;
        a[low] = a[high];
        while(low<high&&a[low]<=key)low++;
        a[high]=a[low];
    }
    a[low] = key;
    if(k<=key)kth_sort(l,low-);
    else kth_sort(low+,r);
}

int main(){
    int n;
    while(~scanf("%d%lld",&n,&k)){
        for(int i=;i<n;i++){
            scanf("%lld",&a[i]);
        }
        int ans = kth_sort(,n-);
        printf("%d\n",ans);
    }
    return ;
}