当前位置: 首页 > news >正文

AcWing 838:堆排序 ← 数组模拟

【题目来源】
https://www.acwing.com/problem/content/840/

【题目描述】
输入一个长度为 n 的整数数列,
从小到大输出前 m 小的数。

【输入格式】
第一行包含整数 n 和 m。
第二行包含 n 个整数,表示整数数列。

【输出格式】
共一行,包含 m 个整数,表示整数数列中前 m 小的数。

【数据范围】
1≤m≤n≤
10^5
1≤数列中元素≤
10^9

【输入样例】
5 3
4 5 1 3 2

【输出样例】
1 2 3

【算法分析】
● 堆是一棵完全二叉树。堆可以用一个一维数组(建议下标从 1 开始)进行模拟。
● 堆的数组模拟实现,参见:https://blog.csdn.net/hnjzsyjyj/article/details/146358448

【算法代码:
堆排序

#include<bits/stdc++.h>
using namespace std;

const int maxn=1e5+5;
int h[maxn];
int tot;
int n,m;

void down(int u) {
    int t=u;
    if(u*2<=tot && h[u*2]<h[t]) t=u*2;
    if(u*2+1<=tot && h[u*2+1]<h[t]) t=u*2+1;
    if(u!=t) {
        swap(h[u],h[t]);
        down(t);
    }
}

int main() {
    cin>>n>>m;
    tot=n;
    for(int i=1; i<=n; i++) cin>>h[i];
    for(int i=n/2; i>=1; i--) down(i);

    while(m--) {
        cout<<h[1]<<" ";
        h[1]=h[tot--];
        down(1);
    }

    return 0;
}

/*
in:
5 3
4 5 1 3 2

out:
1 2 3
*/


【算法代码:sort

#include <bits/stdc++.h>
using namespace std;

const int maxn=1e5+5;
int a[maxn];

int main() {
    int n,m;
    cin>>n>>m;
    for(int i=1; i<=n; i++) cin>>a[i];
    sort(a+1,a+1+n);
    //unique(a+1,a+1+n);

    for(int i=1; i<=m; i++) cout<<a[i]<<" ";

    return 0;
}

/*
in:
5 3
4 5 1 3 2

out:
1 2 3
*/




【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/146331059
https://blog.csdn.net/hnjzsyjyj/article/details/146358448
https://www.acwing.com/solution/content/6362/
https://www.acwing.com/solution/content/5541/





 

相关文章:

  • (C语言)递归求整数的二进制(递归求法)(C语言教学)
  • VSCode创建VUE项目(三)使用axios调用后台服务
  • Android自动化测试终极指南:从单元到性能全覆盖!
  • [免费]SpringBoot+Vue城市交通管理系统【论文+源码+SQL脚本】
  • Visual Studio调试的技巧
  • Python第六章04:列表操作练习题
  • pie保护
  • 什么是 Cache Line?
  • 编译安装redis,systemtcl配置redis自启动,系统并发调优
  • 搭建ISCSI传输的配置与管理
  • JDK 24新特性解读
  • 数据集获取
  • C 语言 第五章 指针(4)
  • Polymer入门指南:从零开始构建、组织、管理Web Component
  • 【机器学习-分类算法】
  • 老知识:OpenGL 的 glu这个库已被弃用,改用glm了
  • 【Azure 架构师学习笔记】- Azure Networking(1) -- Service Endpoint 和 Private Endpoint
  • 操作系统的概念、功能和目标
  • 耘想Docker版Linux NAS的安装说明
  • 存算一体与存算分离:架构设计的深度解析与实现方案
  • 河南省委常委会会议:坚持以案为鉴,深刻汲取教训
  • 白玉兰奖征片综述丨动画的IP生命力
  • 风雨天涯梦——《袁保龄公牍》发微
  • 远如《月球背面》,近似你我内心
  • 工人日报:“鼠标手”被纳入职业病,劳动保障网越织越密
  • 《新时代的中国国家安全》白皮书(全文)