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

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/





 


http://www.kler.cn/a/593931.html

相关文章:

  • 双碳战略下的电能质量革命:解码电力系统的健康密码
  • oracle 索引
  • 世界职业院校技能大赛(软件测试)技术创新思路分享(二)
  • VSCode C/C++ 开发环境完整配置及常见问题
  • Android Launcher3终极改造:全屏应用展示实战!深度解析去除Hotseat的隐藏技巧
  • 数据结构之栈(C语言)
  • 轨道交通DSP+FPGA主控板(6U)板卡,支持逻辑控制、数据处理、通信管理、系统安全保护切换等功能
  • NET6 WebApi第5讲:中间件(源码理解,俄罗斯套娃怎么来的?);Web 服务器 (Nginx / IIS / Kestrel)、WSL、SSL/TSL
  • 【01-驱动学习】
  • 华为流程体系建设与运营(123页PPT)(文末有下载方式)
  • 【Spring 默认是否管理 Request 和 Session Bean 的生命周期?】
  • Android Coil3 Fetcher preload批量Bitmap拼接扁平宽图,Kotlin
  • 头歌 JAVA 桥接模式实验
  • GitHub Actions上关于“Cannot Find Matching Keyid”或“Corepack/PNPM Not Found”的错误
  • 英伟达消费级RTX显卡配置表
  • Linux 驱动开发笔记--1.驱动开发的引入
  • 基于51单片机的多路数据采集系统proteus仿真
  • 效用系统简介
  • bootstrap介绍(前端框架)(提供超过40种可复用组件,从导航栏到轮播图,从卡片到弹窗)bootstrap框架
  • (七)List里面常用的属性和方法