[算法浅析] Algorithm中Heap用法小结
来源:互联网 发布:象牙社区类似的软件 编辑:程序博客网 时间:2024/06/06 12:49
/* 介绍algorithm头文件中根的相关函数
make_heap(首位置, 尾位置+1, 可选的cmp函数); -> 构造堆
push_heap(首位置, 尾位置+1, 可选的cmp函数); -> 添加元素到堆中
pop_heap(首位置, 尾位置+1, 可选的cmp函数); -> 从堆中移出元素
sort_heap(首位置, 尾位置+1, 可选的cmp函数); -> 整个堆进行排序
*/
#include<algorithm>
#include<cstdio>
using namespace std;
bool inc_cmp(int a,int b){ return a > b; }
// 可以理解为:左a右b,当a>b的时候,双方交换位置,
// 所以上式这个cmp意为从小到大(排序)。
bool des_cmp(int a, int b){ return a < b; }
int num[10]={3, 1, 2, 5, 6, 4};
int main()
{
make_heap(num, num+6);//构造一个堆,默认是大根堆。
// 上式等价于make_heap(&num[0], &num[6]);可以看到,区间是[0, 7),
// 即参数中的末尾是真真实末尾的后一个位置。
// 可以修改为make_heap(num, num+6, inc_cmp); 此时为小根堆。
// 插入一个元素到先前创建的堆中,插进来的数将调整到合适的位置。
num[6] = 5;
push_heap(num, num+7);
// pop_heap将堆顶数据移动到末尾位置,然后将剩余数据重新构造堆。
// 其中一个易于理解的例子就是,不断将大根堆堆顶移到末尾,
// 以此模拟从小到大排序。
/* ---------- */
printf("before: ");
for(int i = 0; i < 7; i++)
printf("%d ", num[i]);
printf("\n");
for(int i = 7; i >= 1; i--) // 共7个数,交换到最后第二个数为止。
{
pop_heap(num, num+i);
}
printf("after : ");
for(int i = 0; i < 7; i++)
printf("%d ", num[i]);
printf("\n");
/* ---------- */
//sort_heap,堆排序,因为前面都pop_heap掉了,所以得重新make_heap
make_heap(num, num + 6);
sort_heap(num, num+6, des_cmp);
for(int i = 0; i < 7; i++)
printf("%d ", num[i]);
printf("\n");
return 0;
}
/*
总结:
想要进行堆操作,前提必须是“已构建了堆”。
如果在使用时碰到数据混乱,那么很有可能就是没有make_heap。
需要注意的是make_heap后进行pop_heap操作,那么这个根比原来的"影响范围"就小了,
假设进行上述的"排序"操作,那么这些数据就不再是堆。
想要另行操作只能重新make_heap。
*/
- [算法浅析] Algorithm中Heap用法小结
- Algorithm中Heap
- algorithm中for_each用法
- heap sort algorithm 堆排序算法 java实现
- 浅析 Win2K 中堆(Heap)的实现
- 浅析 Win2K 中堆(Heap)的实现
- 全排列算法(字典序法、SJT Algorithm 、Heap's Algorithm)
- Sorting Algorithm-Heap Sort
- 常用算法(Algorithm)的用法介绍
- 算法 <algorithm>中各种算法解析
- 算法 <algorithm>中各种算法解析
- STL中heap算法(堆算法)
- #include <algorithm>中sort的一般用法
- #include <algorithm>中sort的一般用法
- #include <algorithm>中sort的一般用法
- 关于STL中heap的用法
- golang中container/heap包用法
- algorithm用法
- [杂谈] strtok - 分解输入的字符串
- [C++] C++的运算符重载(+、-、前置--、后置--,前置++,后置++、==)
- [算法浅析] hdu1709的一个优化版母函数
- [C++] 32位C++程序,计算sizeof的值
- [C++] C++作用域
- [算法浅析] Algorithm中Heap用法小结
- [杂谈] 部分常用的algorithm及numeric函数
- [C#] 委托入门
- [杂谈] 回顾switch
- 黑马程序员—JDK1.5新特性(增强for循环、可变参数、静态导入)
- Objective C内存布局
- [算法浅析] 计算循环节
- hdu 1597 find the nth digit
- poj 1129 Channel Allocation