04087: 数据筛选
data structure, http://cs101.openjudge.cn/practice/04087/
总时间限制: 10000ms 单个测试点时间限制: 5000ms 内存限制: 3000kB
描述
小张需要从一批数量庞大的正整数中挑选出第k小的数,因为数据量太庞大,挑选起来很费劲,希望你能编程帮他进行挑选。
输入
第一行第一个是数据的个数n(10<=n<=106),第二个是需要挑选出的数据的序号k(1<=k<=105),n和k以空格分隔; 第二行以后是n个数据T(1<=T<=109),数据之间以空格或者换行符分隔。
输出
第k小数(如果有相同大小的也进行排序,例如对1,2,3,8,8,第4小的为8,第5小的也为8)。
样例输入
10 5 1 3 8 20 2 9 10 12 8 9
样例输出
8
python
import array # Memory Limit Exceed
import heapq
n, k = map(int, input().split())
q = []
cnt = 0
while True:
x = array.array('i', map(int, input().split()))
cnt += len(x)
for i in x:
heapq.heappush(q, -i)
if len(q) > k:
heapq.heappop(q)
if cnt >= n:
break
print(-q[0])该程序的功能是从输入的一组整数中找到第 k 大的数。它使用优先队列来维护当前遍历到的最大的 k 个数,每次将新的数插入到队列中,如果队列的大小超过了 k,则将最大的数移除。最后输出优先队列的顶部元素,即第 k 大的数。
c++
#include <iostream> // time: 340ms
#include <queue>
using namespace std;
int main() {
int n,k,num;
cin>>n>>k;
priority_queue<int> q;
for (int i=0; i<n; ++i) {
cin>>num;
q.push(num);
if (q.size() > k)
q.pop();
}
cout<<q.top()<<endl;
return 0;
}