牛客網 NC207028 第k小數 STL基本用法

1. 題目描述

1.1. Limit

Time Limit: C/C++ 3秒,其他語言6秒

Memory Limit: C/C++ 262144K,其他語言524288K

1.2. Problem Description

給你一個長度爲n的序列,求序列中第k小數的多少。

1.3. Input

多組輸入,第一行讀入一個整數 TT 表示有 TT 組數據。

每組數據佔兩行,第一行爲兩個整數 nkn,k,表示數列長度和 kk

第二行爲 nn 個用空格隔開的整數。

1.4. Output

對於每組數據,輸出它的第 kk 小數是多少。每組數據之間用空格隔開

1.5. Sample Input

2
5 2
1 4 2 3 4
3 3
3 2 1

1.6. Sample Output

2
3

1.7. Note

t10,1n5×106,knt \leq10 , 1\leq n\leq5\times 10^6,k\leq n,數列裏每個數都在int範圍內。

由於輸入比較多,請使用快讀讀取。例如:

inline int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}

1.8. Source

牛客網 NC207028 第k小數

2. 解讀

數據太大了,用STL中的nth_element()函數可以通過,sort()partial_sort() 都會超時。

3. 代碼

#include <algorithm>
#include <iostream>
using namespace std;

const int NUM = 5e6 + 1;

int list[NUM];

inline int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}

// #define DEBUG

int main()
{
#ifdef DEBUG
    freopen("debug/test.txt", "r", stdin);
    freopen("debug/result.txt", "w", stdout);

#endif // DEBUG
    int t, n, k;
    scanf("%d", &t);
    while (t--) {
        scanf("%d %d", &n, &k);
        for (int i = 0; i < n; i++) {
            list[i] = read();
        }

        // 將第k小的數放在 k-1 位置,左邊的數都比它小,右邊的數都比它大,但都是無序的
        nth_element(list, list + k - 1, list + n);
        // 由於數據量太大,下面兩種方法會超時
        // 快速排序
        // sort(list, list + n);
        // 將第k小的數放在 k-1 位置,左邊的數都比它小,而且是有序的,右邊的數都比它大,但右邊是無序的
        // partial_sort(list, list + k - 1, list + n);
        printf("%d\n", list[k - 1]);
    }

    return 0;
}





聯繫郵箱:[email protected]

CSDN:https://me.csdn.net/qq_41729780

知乎:https://zhuanlan.zhihu.com/c_1225417532351741952

公衆號:複雜網絡與機器學習

歡迎關注/轉載,有問題歡迎通過郵箱交流。

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