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
33 24 0 74 21 2 3 42 12 9
Sample Output
427
我一開始的思路是直接將所有想減的絕對值丟進一個數組,再快排,果然是逾時了
再看了下人家的程式,真心的,只能說思維比我靈活多了,菜鳥真心傷不起啊!
#include <iostream>#include <cstdio>#include <stdlib.h>#include <cstring>using namespace std;int cmp(const void *x,const void *y){ return (*(int *)x - *(int *)y);}int main(){ int t,a[1005],hash[2005]; cin >> t; while(t--) { memset(a,0,sizeof(a)); memset(hash,0,sizeof(hash)); int n,k,i,j,m = 0; cin >> n >> k; for(i = 1;i<=n;i++) cin >> a[i]; int num = 0,flag = 1; qsort(a+1,n,sizeof(int),cmp); for(i = 1;i<n;i++) { for(j = 1;i+j<=n;j++) { hash[a[i+j]-a[j]]++;//a[i+j]-a[j]就是題目中的|xi-xj| } } int z = 0; for(int x = 0;x<=2000;x++) { if(hash[x]) { z++;//統計位置 if(z == k) { cout << x << endl; break; } } } } return 0;}