HDU-1425-sort(计数排序以及快速排序和堆排序的变种)

  • 计数排序
    Accepted 1425 483MS 5276K 997 B G++
    #include "bits/stdc++.h"
    using namespace std;
    typedef long long LL;
    typedef pair<int, int> PII;
    const int INF = 0x3f3f3f3f;
    const int MAXN = 1e6 + 5;
    const int MIN_NUM = -5e5;
    const int MAX_NUM = 5e5;
    // MAX_NUM - MIN_NUM 表示输入数字的范围
    int num[MAX_NUM - MIN_NUM + 10];
    int main() {
        int n, m, k;
        while (~scanf("%d%d", &n, &m)) {
            while (n--) {
                scanf("%d", &k);
                // 因为存在负数而没有负下标,所以将所有输入的数减去MIN_NUM然后再存入对应下标
                num[k - MIN_NUM]++;
            }
            k = MAX_NUM - MIN_NUM;
            while (m--) {
                while (num[k] == 0) {
                    k--;
                }
                num[k]--;
                if (m != 0) {
                    printf("%d ", k + MIN_NUM);
                } else {
                    printf("%d\n", k + MIN_NUM);
                }
            }
            // k后面的都已经清空了所以,这里只要清空k前面这段就好了;
            memset(num, 0, sizeof(int) * (k + 1));
        }
        return 0;
    }

    计数排序适用于排序范围已知且排序数量大,排序范围小的情况。复杂度为Ο(n+k)。n表示排序数量,k表示排序范围;

猜你喜欢

转载自www.cnblogs.com/Angel-Demon/p/10297768.html