CSU 1867 中南大學網路賽F題 John and Health rate
題目:
Description
The cold and flu season is here.John is worried about his cow. In order to monitor the situation of his cow,he do some inspecting everyday,and record the “health rate” for each cow.The “health rate” is a integer which can show the cow’s health condition.The higher a cow’s health rate is ,the healthier the cow is.What’s more,the doctor told John that the k-th small health rate is dangerous.Because the doctor thought there are at most k healthy cows. So John has to find out which number is the k-th small.Can you help him?
Input
Input contains multiple test cases.
The first line contains two integers n,k (1 ≤ n ≤ 1000000,1<=k<=n) — the number of cows and dangerous number. The second line contains n integers,and the i-th integer ai(-10000<=ai<=10000) is the i-th cow’s health rate
Output
Output a single line with the k-th small health rate.
Sample Input
2 1
3 2
5 2
-1 0 -2 5 3
Sample Output
2
-1
就是輸入n,k,然後輸入n個數,要求輸出從小到大第k個數。
線性時間選擇的演算法是比較複雜的,這裡不需要,因為給出了每個數的範圍,所以只需要20001個桶即可。
程式碼:#include<iostream>
using namespace std;
int num[20001];
int main()
{
int n, k, h, key;
while (cin >> n >> k)
{
for (int i = 0; i <= 20000; i++)num[i] = 0;
for (int i = 0; i < n; i++)
{
scanf("%d", &h);
num[h + 10000]++;
}
key = 0;
while (k>num[key])k -= num[key++];
cout << key - 10000 << endl;
}
return 0;
}