牛客网 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

公众号:复杂网络与机器学习

欢迎关注/转载,有问题欢迎通过邮箱交流。

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