寻找大富翁

题目描述

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

输入描述:

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

输出描述:

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

分析

当自己写的O(n^2)的排序时间过长时,可以调用c++ STL的sort()函数,具体见sort() 函数的用法

#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;

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

int main() {
    int n, m;
    int fortune[100000];
    while(cin >> n >> m){
        for(int i = 0; i < n; i++){
            cin >> fortune[i];
        }
        sort(fortune,fortune+n+1,cmp);
        int index = m;
        index = n < m ? n : m;
        for(int i = 0; i < index - 1; i++){
            cout << fortune[i] << " ";
        }
        cout << fortune[index - 1] << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zhuobo/p/10207683.html