zoukankan      html  css  js  c++  java
  • 数据结构与算法题目集(中文)7-38 寻找大富翁 (25分) (sort函数、优先队列进行排序)

    1.题目

    胡润研究院的调查显示,截至2017年底,中国个人资产超过1亿元的高净值人群达15万人。假设给出N个人的个人资产值,请快速找出资产排前M位的大富翁。

    输入格式:

    输入首先给出两个正整数N(≤10​6​​)和M(≤10),其中N为总人数,M为需要找出的大富翁数;接下来一行给出N个人的个人资产值,以百万元为单位,为不超过长整型范围的整数。数字间以空格分隔。

    输出格式:

    在一行内按非递增顺序输出资产排前M位的大富翁的个人资产值。数字间以空格分隔,但结尾不得有多余空格。

    输入样例:

    8 3
    8 12 7 3 20 9 5 18
    

    输出样例:

    20 18 12

    2.题目分析

    1.思路:快排或者堆排序

    2.实现:sort或者priority_queue

    3.注意:N居然还可以小于M 我嘤嘤嘤??

    4.注注意意:sort函数中使用greater<int>():sort(list.begin(), list.end(), greater<int>());是逆序输出

    而priority_queue中greater<int>()是正序输出注意区别

    3.代码

    sort

    #include<iostream>
    #include<cstdio>
    #include<vector>
    #include<functional>
    #include<algorithm>
    using namespace std;
    vector<int>list;
    int main()
    {
    	int n, m;
    	cin >> n >> m;
    	for (int i = 0; i < n; i++)
    	{
    		int temp;
    		scanf("%d", &temp);
    		list.push_back(temp);
    	}
    	sort(list.begin(), list.end(), greater<int>());
    	int count = 0;
    	int count2 = 0;
    	vector<int>::iterator run;
    	for (run = list.begin();count2<m&& run != list.end(); run++)
    	{
    		if (count == 0)
    		{
    			printf("%d", *run); count++;
    		}
    		else
    			printf(" %d", *run);
    		count2++;
    	}
    
    }

    priority_queue

    #include<iostream>
    #include<queue>
    #include<cstdio>
    using namespace std;
    int main()
    {
    	int n, m;
    	cin >> n >> m;
    	priority_queue<int>list;
    	int temp;
    	for (int i = 0; i < n; i++)
    	{
    		scanf("%d",&temp);
    		list.push(temp);
    	}
    	int count = 0;
        if(n<m)m=n;
    	for (int i = 0; i < m; i++)
    	{
    		int temp2 = list.top(); list.pop();
    		if (count == 0)
    		{
    			printf("%d", temp2);
    			count++;
    		}
    		else
    			printf(" %d", temp2);
    	}
    	cout << endl;
    
    }
  • 相关阅读:
    ASP.NET 自制时间控件
    ORACLE 函数汇总之单记录函数
    Servers IIS 重启命令
    ASP.NET 两个Dropdownlist控件联动
    ASP.NET datagridview控件表头定义
    python Image 安装
    ssh 不需要密码的链接
    [Redis] redis 相关的博客
    [emacs] python代码折叠
    linux python 链接 oracle
  • 原文地址:https://www.cnblogs.com/Jason66661010/p/12789000.html
Copyright © 2011-2022 走看看