文章目錄
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
多組輸入,第一行讀入一個整數 表示有 組數據。
每組數據佔兩行,第一行爲兩個整數 ,表示數列長度和 。
第二行爲 個用空格隔開的整數。
1.4. Output
對於每組數據,輸出它的第 小數是多少。每組數據之間用空格隔開
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
,數列裏每個數都在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
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
公衆號:複雜網絡與機器學習
歡迎關注/轉載,有問題歡迎通過郵箱交流。