当前位置:网站首页>1098 Insertion or Heap Sort (25 分)
1098 Insertion or Heap Sort (25 分)
2022-06-29 09:23:00 【陌陌623】
题解
现在脑子比较慢,看了柳神的题解,她的题解真的太好看了
看一遍 感觉不到多余的代码 并且可读性强
在这里写博,仅是个人的笔记使用
并且感觉写博客有助于清晰思路
题解
需要两种情况:
- 插入排序:前几个元素是顺序的,后几个元素和初始序列的顺序一致
- 堆排序 :后几个元素是顺序的,前几个元素是一个大顶堆
解决:
- 插入排序:找到两个部分(顺序和不是顺序)的分界点 对前几个元素的个数+1 的个数 行进sort
- 堆排序 :找到分界点,很容易发现,b[1]是大顶堆的最大值,而一定是已经排过序的元素的最小值
故,从后先前找即可
Code
#include <iostream>
#include <algorithm>
using namespace std;
const int n = 110;
int a[n], b[n];
int N;
int get_index()
{
int i = 1;
while (i <= N && b[i - 1] <= b[i])
i++;
int index = i;
while (i <= N && a[i] == b[i])
i++;
return (i == N + 1 ? index : 0);
}
int main()
{
cin >> N;
for (int i = 1; i <= N; i++)
cin >> a[i];
for (int i = 1; i <= N; i++)
cin >> b[i];
int index = get_index();
if (index)
{
cout << "Insertion Sort\n";
sort(b + 1, b + index + 1);
}
else
{
cout << "Heap Sort\n";
index = N;
while (index >= 2 && b[index] >= b[1])
index--;
swap(b[index], b[1]);
// 建立堆函数
// 直接将前几个 做一个堆就行
make_heap(b + 1, b + index);
}
for (int i = 1; i <= N; i++)
{
if (i != 1)
cout << " ";
cout << b[i];
}
return 0;
}
边栏推荐
猜你喜欢

JVM method return address

任务调度器之Azkaban的使用

Flutter 基础组件之 GridView

FreeRTOS(九)——队列

RecyclerView 粘性(悬浮)头部

基辅周边的凄美废墟——切尔诺贝利的安全前往指南!

Gmail:如何快速将邮件全部已读

Install and configure redis in the Linux environment, and set the boot auto start

Zabbix4.4 configure the indicators of the monitoring server and solve the garbled graphics pages

Container of the basic component of the flutter
随机推荐
container
另类实现 ScrollView 下拉头部放大
Flutter 基础组件之 Container
RecyclerView 粘性(悬浮)头部
自定义控件之侧滑关闭 Activity 控件
使用Rancher搭建Kubernetes集群
acwing271【杨老师的照相排列】【线性DP】
2019icpc上海区域赛赛后总结
gcc与makefile
Leetcode MySQL database topic 177
C语言实现一种创建易管理易维护线程的方法
Leetcode MySQL database topic 178
Caused by: org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8
Time varying and non time varying
JNI.h说明
HDU 4578 Transformation(线段树+有技巧的懒标记下放)
Pointer functions and function pointers
ImageView图片填充问题
任务调度器之Azkaban的使用
JVM之虚拟机栈之动态链接