链接:https://vjudge.net/problem/HDU-1425

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

Input

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

Output

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

Sample

input:

1
2
5 3
3 -35 92 213 -644

output:

1
213 92 3

Solution

本题要排序的n个数不相同,如果使用通用排序会time limit,需要做特殊设计。 用一个长数组做位置编码,用memset初始化为0,读到一个数就将对应位置置为1。 注意:数的取值范围是[-500000,500000],所以数组长度应为1000000+1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<cstdio>
#include<cstring>
using namespace std;
const int MAX=1000000;
const int BIAS=500000;
bool nums[MAX+1];
int main(){
  int N,M,value;
  while(scanf("%d%d",&N,&M)!=EOF){
    memset(nums,0,sizeof(nums));
    for(int i=0; i<N; ++i){
      scanf("%d",&value);
      nums[value+BIAS]=1;
    }
    for(int i=MAX; i>=0; --i){
      if(nums[i]){
        if(M>1){printf("%d ",i-BIAS); --M;}
        else   {printf("%d\n",i-BIAS); break;}
      }
    }
  }
  return 0;
}