这个题的话,使用堆排拿头,刚好复习下堆排序的概念以及写法
#include<iostream> #include<string.h> #include<algorithm> using namespace std; //尝试使用小根堆去解决这个问题 int heap[1005]; int heap_size=0; void put(int d){ int now,next; heap[++heap_size]=d; now=heap_size; while(now>1){ next=now>>1; if(heap[now]>=heap[next]) break; swap(heap[now],heap[next]); now=next; } } int get(){ int now=1,next,res=heap[1]; heap[1]=heap[heap_size--]; while(now*2<=heap_size){ next=now*2; if(next<heap_size&&heap[next+1]<heap[next]) next++; if(heap[now]<=heap[next]) break; swap(heap[now],heap[next]); now=next; } return res; } int main(){ int n,k,tmp; while(cin>>n>>k){ memset(heap,0,sizeof(heap)); heap_size=0; for(int i=0;i<n;i++){ cin>>tmp; put(tmp); } while(k--){ cout<<get()<<" "; } cout<<endl; } return 0; }