优先队列的底层是大顶堆,改成小顶堆、全体压入、再弹出k个即可
注意权值相同时是并列的
#include<stdio.h> #include<queue> using namespace std; int main(){ int n,k; int temp; while(scanf("%d",&n)!=EOF){ priority_queue<int,vector<int>,greater<int>> queue; for(int i=0;i<n;i++){ scanf("%d",&temp); queue.push(temp); } scanf("%d",&k); if(k==1){ return queue.top(); } else { int counter = 1; int pre = queue.top(); queue.pop(); while(counter<=k){ int current = queue.top(); if(current!=pre) counter++; if(counter==k) break; queue.pop(); pre = current; } printf("%d\n",queue.top()); } } return 0; }