HDU - 3785 寻找大富翁

Description

浙江桐乡乌镇共有n个人,请找出该镇上的前m个大富翁.

Input

输入包含多组测试用例.
每个用例首先包含2个整数n(0<n<=100000)和m(0<m<=10),其中: n为镇上的人数,m为需要找出的大富翁数, 接下来一行输入镇上n个人的财富值.
n和m同时为0时表示输入结束.

Output

请输出乌镇前m个大富翁的财产数,财产多的排前面,如果大富翁不足m个,则全部输出,每组输出占一行.

Sample Input

3 1
2 5 -1
5 3
1 2 3 4 5
0 0

Sample Output

5
5 4 3
#include <iostream>
#include <algorithm>
#include <stdio.h>

using namespace std;

bool cmp(int a, int b){
    return a > b;
}
int a[100005];

int main()
{
    int n, m;
    while (~scanf("%d %d", &n, &m) && !(n==0&&m==0)){
        for (int i = 0; i < n; i++)
            scanf("%d", &a[i]);
        if (n > m){
            for (int i = 0; i < m; i++)
                for (int j = i+1; j < n; j++)
                    if (a[i] < a[j])
                        swap(a[i], a[j]);
            printf("%d", a[0]);
            for (int i = 1; i < m; i++)
                printf(" %d", a[i]);
        } else {
            sort(a, a+n, cmp);
            printf("%d", a[0]);
            for (int i = 1; i < n; i++)
                printf(" %d", a[i]);
        }
        printf("\n");
    }
    return 0;
}
发布了339 篇原创文章 · 获赞 351 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/Aibiabcheng/article/details/105353876
今日推荐