HDU1280 前m大的數【排序】

前m大的數

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

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

Source
杭電ACM集訓隊訓練賽(VI)

問題鏈接HDU1280 前m大的數
問題簡述:(略)
問題分析
    2個數和值範圍比較小,就可以使用計數排序。
    有兩種排序解決方法,一是計數排序(一般被稱作桶排序),其時間複雜度爲O(n),代碼邏輯略微複雜;二是使用排序,輸出最大的n個數即可。
程序說明:(略)
參考鏈接:(略)
題記:(略)

AC的C++語言程序(計數排序)如下:

/* HDU1280 前m大的數 */

#include <bits/stdc++.h>

using namespace std;

const int N = 3000;
int a[N];
const int M = 5000;
int cnt[M + M + 1];

int main()
{
    int n, m;
    while(~scanf("%d%d", &n, &m)) {
        for(int i = 0; i < n; i++) scanf("%d", &a[i]);

        memset(cnt, 0, sizeof(cnt));
        for(int i = 0; i < n; i++)
            for(int j = i + 1; j < n; j++)
                cnt[a[i] + a[j]]++;

        int i;
        for(i = M + M; i >= 0 && m >= 1; i--) {
            while(cnt[i]) {
                if(m-- == 1) {
                    printf("%d\n", i);
                    break;
                } else {
                    printf("%d ", i);
                    cnt[i]--;
                }
            }
        }
    }

    return 0;
}

AC的C++語言程序(排序)如下:

/* HDU1280 前m大的數 */

#include <bits/stdc++.h>

using namespace std;

const int N = 3000;
int a[N];
const int M = 5000;
int sum[M * M / 2];

int main()
{
    int n, m;
    while(~scanf("%d%d", &n, &m)) {
        for(int i = 0; i < n; i++) scanf("%d", &a[i]);

        int cnt = 0;
        for(int i = 0; i < n; i++)
            for(int j = i + 1; j < n; j++)
                sum[cnt++] = a[i] + a[j];

        sort(sum, sum + cnt);

        for(int i = cnt - 1; i > cnt - m; i--)
            printf("%d ", sum[i]);
        printf("%d\n", sum[cnt - m]);
    }

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