当前位置:网站首页>1098 insertion or heap sort (25 points)
1098 insertion or heap sort (25 points)
2022-06-29 10:13:00 【Momo 623】
Answer key
Now the brain is slow , After reading Liu Shen's explanation , Her explanation is really beautiful
work through Don't feel superfluous code And it's very readable
Blog here , For personal notes only
And I feel that blogging helps clear your mind
Answer key
Two situations are required :
- Insertion sort : The first few elements are sequential , The last few elements are in the same order as the initial sequence
- Heap sort : The last few elements are sequential , The first few elements are a big top heap
solve :
- Insertion sort : Find two parts ( Sequence and are not sequence ) The dividing point of For the number of the first few elements +1 The number of March on sort
- Heap sort : Find the dividing point , It's easy to see ,b[1] Is the maximum value of the large top stack , It must be the minimum value of the ordered elements
so , From the back to the front
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]);
// Build heap functions
// The first few Just make a heap
make_heap(b + 1, b + index);
}
for (int i = 1; i <= N; i++)
{
if (i != 1)
cout << " ";
cout << b[i];
}
return 0;
}
边栏推荐
猜你喜欢
随机推荐
阿里云防火墙配置,多种设置方式(iptables和fireward)
RecyclerView 通用适配器封装
A method of creating easy to manage and maintain thread by C language
六度空间 bfs
Pointer functions and function pointers
RecyclerView刷新闪烁与删除Item时崩溃问题
Leetcode MySQL database topic 178
Flutter 基础组件之 Container
In XML layout, the button is always displayed on the top layer
RecyclerView 粘性(悬浮)头部
51nod1277 maximum value in string [KMP]
520 钻石争霸赛 2021
The Stones Game【取石子博弈 & 思维】
1021 Deepest Root (25 分)
任务调度器之Azkaban的使用
2019.10.20训练总结
L2-031 深入虎穴 (25 分)
Is flush stock trading software reliable and safe?
JVM之方法返回地址
Codeforces Round #652 (Div. 2)








