HDU1425 sort

来源:互联网 发布:linux命令文件命名 编辑:程序博客网 时间:2024/05/16 05:34

sort
原文链接:HDU1425 sort
Time Limit: 6000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 50532 Accepted Submission(s): 14324

Problem Description
给你n个整数,请按从大到小的顺序输出其中前m大的数。

Input
每组测试数据有两行,第一行有两个数n,m( 0 < n,m<1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数。

Output
对每组测试数据按从大到小的顺序输出前m大的数。

Sample Input
5 3
3 -35 92 213 -644

Sample Output
213 92 3

Hint
请用VC/VC++提交

分析:采用快速排序,只对前m个元素排序,节省时间。

#include<stdio.h>#define max 1000000int f(int arr[],int l,int h){    int m=arr[l];    while(1)    {        while(l<h&&m>=arr[h]) //从最右面寻找比m小的数,并与arr[l]替换             h--;        if(l>=h)            break;        arr[l++]=arr[h];        while(l<h&&arr[l]>=m)//从左往右寻找比m大的数并与arr[h]替换             l++;        if(l>=h)            break;        arr[h--]=arr[l];     }    arr[h]=m;//h为最终m的插入点下标     return h;}void sort(int arr[],int l,int h,int m){    int q;    if(l>h) return;    q=f(arr,l,h);    sort(arr,l,q-1,m);    if(q+1<m)    sort(arr,q+1,h,m);}void display(int arr[],int n){    int i;    for(i=0;i<n;i++)    {        if(i)            printf(" ");        printf("%d",arr[i]);    }    printf("\n"); }int main(){    int arr[max],i,n,m;    printf("11");    while(scanf("%d %d",&n,&m)!=EOF)    {        for(i=0;i<n;i++)            scanf("%d",&arr[i]);        sort(arr,0,n-1,m);        display(arr,m);    }    return 0;}
原创粉丝点击