杭电2523

Problem Description
给你N个整数,x1,x2...xn,任取两个整数组合得到|xi-xj|,(0<i,j<=N,i!=j)。
现在请你计算第K大的组合数是哪个(一个组合数为第K大是指有K-1个不同的组合数小于它)。

Input
输入数据首先包含一个正整数C,表示包含C组测试用例.
每组测试数据的第一行包含两个整数N,K。(1<N<=1000,0<K<=2000)
接下去一行包含N个整数,代表x1,x2..xn。(0<=xi<=2000)

Output
对于每组测试数据,请输出第K大的组合数,每个输出实例占一行。

Sample Input
3
3 2
4 0 7
4 2
1 2 3 4
2 1
2 9

Sample Output
4
2
7

#include<stdio.h>
#include<string.h>
#define AMAXINDEX 1000
#define BMAXINDEX 2000
int Partition(int *L,int low,int high);
void QSort(int *L,int low,int high);//快速排序
int main(){
    int C,N,K,a[AMAXINDEX],b[BMAXINDEX],vv[BMAXINDEX],p,m;
    scanf("%d",&C);
    while(C--){
        memset(vv,0,BMAXINDEX*sizeof(int));
        p=0;
        scanf("%d",&N);
        scanf("%d",&K);
        for(int i=0;i<N;i++){
            scanf("%d",&a[i]);
        }
        for(int i=0;i<N-1;i++){
            for(int j=i+1;j<N;j++){
                int m=abs(a[i]-a[j]);
                if(vv[m]==0){
                    b[p++]=m;
                    vv[m]=1;
                }
            }
        }
        if(p==1){
             printf("%d\n",b[0]);
             continue;
        }
        QSort(b,0,--p);
        printf("%d\n",b[K-1]);
        }
        return 0;
    }


int Partition(int *L,int low,int high){
    int pivotkey;
    pivotkey=L[low];
    while(low<high){
        while(low<high&&L[high]>=pivotkey)
            high--;
        int temp1;
        temp1=L[low];
        L[low]=L[high];
        L[high]=temp1;
        while(low<high&&L[low]<=pivotkey)
            low++;
        int temp2;
        temp2=L[low];
        L[low]=L[high];
        L[high]=temp2;
    }
    return low;
}

void QSort(int *L,int low,int high){
    int pivot;
    if(low<high){
         pivot=Partition(L,low,high);
         QSort(L,low,pivot-1);
         QSort(L,pivot+1,high);
    }
}


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容