前m大的數(HDU_1280) 計數排序

前m大的數

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15953    Accepted Submission(s): 5450


Problem Description
還記得Gardon給小希佈置的那個作業麼?(上次比賽的1005)其實小希已經找回了原來的那張數表,現在她想確認一下她的答案是否正確,但是整個的答案是很龐大的表,小希只想讓你把答案中最大的M個數告訴她就可以了。 
給定一個包含N(N<=3000)個正整數的序列,每個數不超過5000,對它們兩兩相加得到的N*(N-1)/2個和,求出其中前M大的數(M<=1000)並按從大到小的順序排列。
 

Input
輸入可能包含多組數據,其中每組數據包括兩行: 
第一行兩個數N和M, 
第二行N個數,表示該序列。

 

Output
對於輸入的每組數據,輸出M個數,表示結果。輸出應當按照從大到小的順序排列。
 

Sample Input
4 4 1 2 3 4 4 5 5 3 6 4
 

Sample Output
7 6 5 5 11 10 9 9 8
 

Author
Gardon


題目大意:按從大到小輸出n個數兩數自和;

解題思路:計數排序。

#include"iostream"
#include"cstdio"
#include"cstring"
using namespace std;
const int maxn = 10005;

int cnt[maxn];
int num[3005];

int max(int x, int y){
	return x > y ? x : y;
}

int main(){
	int n, k, t, max_sum;
	while(scanf("%d%d", &n, &k) != EOF){
		memset(cnt, 0, sizeof cnt);
		max_sum = 0;
		for(int i = 1;i <= n;i ++)
			scanf("%d", &num[i]);
		//if(k == 0) continue;
		for(int i = 1;i <= n-1;i ++)
			for(int j = i+1;j <= n;j ++){
				t = num[i] + num[j];
				cnt[t] ++;
				max_sum = max(t, max_sum);
			}
		int r = max_sum, f = 0;
		while(k){
			while(cnt[r]&&k){
				if(f == 0) printf("%d", r);
				else printf(" %d", r);
				f = 1;
				cnt[r] --;
				k --;
			}
			r --;
		}
		printf("\n");
	}
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章