1 2 3 4
推荐指数:※※
来源:http://ac.jobdu.com/problem.php?pid=1371
快速排序的前k个结果。注意,当pivot的值大于k时,从(j+1,high)之间的数就不需要处理了。
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> using namespace std; #define LL long long void swap(LL *a, LL *b){ LL tmp=*a; *a=*b; *b=tmp; } int partition_arr(int low,int high,LL *arr,const int k){ if(low>=high) return 0; LL tmp=arr[low]; int i=low,j=high+1; LL pivot=arr[low]; while(1){ while(arr[++i]<pivot); while(arr[--j]>pivot); if(i<j) swap(arr[i],arr[j]); else break; } swap(arr[low],arr[j]); if(low<j-1) partition_arr(low,j-1,arr,k); if(j+1<high&&j+1<=k) partition_arr(j+1,high,arr,k); return 0; } int main() { int n,k,i; while(~scanf("%d%d",&n,&k)){ LL *arr=new LL [n]; for(i=0;i<n;i++) scanf("%lld",&arr[i]); partition_arr(0,n-1,arr,k-1); if(n>=k){ printf("%d",arr[0]); for(i=1;i<k;i++) printf(" %lld",arr[i]); printf("\n"); } } return 0; }
使用最大堆
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<queue> #include<vector> #include<stack> using namespace std; #define LL long long void swap(LL *a, LL *b){ LL tmp=*a; *a=*b; *b=tmp; } struct cmp{ bool operator()(LL a,LL b){ return a<b; } }; void find_k(LL *arr,int len,int k,priority_queue<LL,vector<LL>,cmp> *heap){ int i; for(i=0;i<len;i++){ if((*heap).size()>=k){ if((*heap).top()>arr[i]){ (*heap).pop(); (*heap).push(arr[i]); } } else (*heap).push(arr[i]); } } void print_heap(priority_queue<LL,vector<LL>,cmp> *heap){ stack<LL> s; while(!(*heap).empty()){ s.push((*heap).top()); (*heap).pop(); } if(!s.empty()){ printf("%lld",s.top()); s.pop(); while(!s.empty()){ printf(" %lld",s.top()); s.pop(); } } } int main() { int n,k,i; while(~scanf("%d%d",&n,&k)){ LL *arr=new LL [n]; for(i=0;i<n;i++) scanf("%lld",&arr[i]); if(n>=k){ priority_queue<LL,vector<LL>,cmp> heap; find_k(arr,n,k,&heap); print_heap(&heap); printf("\n"); } } return 0; }