c++ STL二叉堆(优先队列)

c++ STL二叉堆(优先队列)

1.介绍

完全二叉树:叶子节点只会出现在最后2层,且最后一层的叶子节点都靠左对齐。

在这里插入图片描述

二叉堆 (优先队列):一种特殊的完全二叉树,父结点值比子结点大或者小

最小堆(小根堆):父结点比子结点都要小

最大堆(大根堆):父结点比子结点都要大

二叉堆前提是他必须是一颗完全二叉树!!!!!

在这里插入图片描述

既然可以按顺序标号,那么我们就可以用一个数组来把这颗树存起来了

在这里插入图片描述

根节点下标为1,左孩子下标 父结点下标*2 ,右孩子下标 父结点下标*2+1

反过来,我们知道孩子的下标,求父结点的下标 孩子的下标 / 2

如果这是最小堆最小元素就是 数组[1]; 反之,最大堆最大的 数组[1];

2.手写堆(可以跳过直接看3)

样例堆如下图:
在这里插入图片描述

删除元素:(删除1)

让堆顶的结点和最后一个元素交换,再删除最后一个元素,最后对堆进行调整(下沉);

在这里插入图片描述

void down( int i ) 
{
    int t, flag = 1;//flag来标记符不符合堆的特性
    while ( i * 2 <= n && flag ) {
        t = i*2;//左孩子
        if ( i * 2 + 1 <= n ) { //有右孩子
            if ( h[i*2] > h[i*2+1] ) {
                t = i*2+1;
            }
        }
        if ( h[t] > h[i] ) {
            flag = 0;
        }
        else {
            swap(t, i);//交换下标t,i的数组元素
            i = t;
        }
    }
}
void delete()
{
    swap(1, n); //交换下标为1 和 n的元素
    n--;//堆的size-1
    down(1);   //下沉
}

插入元素

插入元素:插入元素0

先让n++,h[n] = 0, 再对0进行上浮

在这里插入图片描述

void up( int i)//上浮下标为i的元素
{
    if ( i == 1 ) return ;//i=1就是根节点嘛
    
    int flag = 1;
    while ( i != 1 && flag ) {
        if ( h[i] < h[i/2] ) {
            swap(i, i/2);
        }
        else {
            flag = 0;
        }
        i /= 2;  //i要时刻跟踪着我们插入的结点
    }
}
void insert( int x ) 
{
    n++;
    h[n] = x;//h数组表示存结点的数组
    up(n);
}

创建堆:

先用数组存起来所有元素,然后从倒数第二层依次下沉:

void create()
{
    //n为堆中最后一个结点的位置,
	for ( int i = n/2; i >= 1; --i ) {
        down(i);
    }    
}

完整代码

#include <iostream>
//堆的基本常规操作

using namespace std;
int n, h[105];

//交换下标元素
void swap( int i, int j);
//下沉
void down( int i );
void delete1();

//上浮
void up( int i );
void insert( int x );

//创建堆
void create();

//主函数
int main()
{
	cin >> n;
	for ( int i = 1; i <= n; ++i ) {
		cin >> h[i];
	}
	create();
	
	for ( int i = 1; i <= n; ++i ) {
		cout << h[i] << ' ';
	}
	return 0;
}

void swap( int i, int j)
{
	int temp = h[i];
	h[i] = h[j];
	h[j] = temp;
}

void delete1()
{
	swap(1, n);
	n--;
	down(1);
}

void down( int i )
{
	int t, flag = 1;
	while ( i * 2 <= n && flag ) {
		//表示左孩子的下标
		t = i * 2;
		//在判断有没有右孩子
		if ( i * 2 + 1 <= n ) {
			if ( h[i*2+1] < h[i*2] ) {
				t = i*2+1;
			}
		}
		if ( h[t] > h[i] ) {
			flag = 0;
		}
		else {
			swap(i, t);
			i = t;
		}
	}
}
void insert( int x )
{
	n++;
	h[n] = x;
	up(n);
}
void up( int i )
{
	//如果i等于1,直接跳出循环
	if ( i == 1 ) return ;
	
	int flag = 1;
	while ( i != 1 && flag ) {
		if ( h[i] < h[i/2] ) {
			swap(i, i/2);
			i /= 2;
		}
		else {
			flag = 0;
		}
	}
}

void create()
{
	for ( int i = n/2; i >= 1; --i ) {
		down(i);
	}
}

3.STL优先队列

priority_queue<int, vector< int>, greater< int> > q; //最小堆

priority_queue<int, vector< int>, less< int> > c; //最大堆

基本操作:

方法用途
top()访问队头元素,只是访问
empty()队列是否为空
size()返回队列内元素个数
push()插入元素到队尾 (并排序)
pop()弹出队头元素,无返回值
emplace()原地构造一个元素并插入队列
swap()交换内容

定义:priority_queue<类型,容器方式,比较方法> q;

例子:priority_queue<int, vector< int>, greater< int> > q;

容器方式STL里面默认用的是vector;

类型可以自定义;

c++默认是一个最大堆 priority_queue<int, vector< int> > q 等同于 priority_queue< int, vector< int>, less< int> > q

#include <iostream>
#include <queue>
using namespace std;

//定义优先队列a,b,c,事实上三者一毛一样的
priority_queue<int> a;
priority_queue<int, vector<int> > b;//默认vector
priority_queue<int, vector<int>, less<int> > c; //默认less

int main()
{
	for ( int i = 0; i < 5; ++i ) {
		a.push(i);//加入元素
		b.push(i);
		c.push(i);
	}
	
	cout << "A:";
	while ( !a.empty() ) {
		cout << a.top() << ' ';
		a.pop();
	}
	cout << endl;
	
	cout << "B:";
	while ( !b.empty() ) {
		cout << b.top() << ' ';
		b.pop();
	}
	cout << endl;
	
	cout << "C:";
	while ( !c.empty() ) {
		cout << c.top() << ' ';
		c.pop();
	}
	cout << endl;
	
	return 0;
}

来一个类型为pair的,默认是先比较第一个,在比较第二个

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() 
{
    priority_queue<pair<int, int> > a;
    pair<int, int> b(1, 2);
    pair<int, int> c(1, 3);
    pair<int, int> d(2, 5);
    a.push(d);
    a.push(c);
    a.push(b);
    while (!a.empty()) 
    {
        cout << a.top().first << ' ' << a.top().second << '\n';
        a.pop();
    }
}

//如果pair里面的类型是我们自定义的,c++没有给我们准备比较规则,那么我们就要自己写比较规则了

自定义比较方法

看看优先队列定义:

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

参数3需要指定一个实现了 operator< 操作符的类(叫做仿函数或者函数对象,实际上就是类,只是调用时写起来像函数一样)

假如我们不想用c++的greater,我们要自己写,自己来做最小堆

#include <iostream>
#include <queue>
using namespace std;

struct cmp{
	//左边是队尾,右边是队首
	//即队首b 小于 其他元素
	//最小堆
	bool operator () ( int a, int b ) {
		return b < a;
	}
};

int main()
{
	priority_queue<int, vector<int>, cmp> c;
	
	for ( int i = 0; i < 5; ++i ) {
		c.push(i);
	}
	
	cout << "C:";
	while ( !c.empty() ) {
		cout << c.top() << ' ';
		c.pop();
	}
	cout << endl;
	
	return 0;
}

自定义类型

less

#include <iostream>
#include <queue>
#include <string>
using namespace std;

//学生,假设年龄小的优先级高
//年龄相同,按姓名字典序
typedef struct Student{
	int age;
	string name;
}Stu;
//b是队首元素
bool operator < (Stu a, Stu b)
{
	if (a.age == b.age) return b.name > a.name;//按字典序来看优先级
	return b.age < a.age;//年龄小的优先级高
}

int main()
{
	priority_queue<Stu, vector<Stu>, less<Stu> > c;  //================>这里是less,就重写小于
	
	for ( int i = 0; i < 5; ++i ) {
		Stu a = {i, "s"};
		c.push(a);
	}
	
	cout << "C:\n";
	while ( !c.empty() ) {
		cout << c.top().name << ' ' << c.top().age << endl;
		c.pop();
	}
	cout << endl << endl;
	
	Stu a = {10, "田小锋"}; c.push(a);
	Stu b = {10, "田小锋01"}; c.push(b);
	cout << "C:\n";
	while ( !c.empty() ) {
		cout << c.top().name << ' ' << c.top().age << endl;
		c.pop();
	}
	cout << endl;
	
	return 0;
}

greater

#include <iostream>
#include <queue>
#include <string>
using namespace std;

//学生,假设年龄小的优先级高
//年龄相同,按姓名字典序
typedef struct Student{
	int age;
	string name;
}Stu;
//b是队首元素
bool operator > (Stu a, Stu b)
{
	if (a.age == b.age) return b.name > a.name;//按字典序来看优先级
	return b.age < a.age;//年龄小的优先级高
}

int main()
{
	priority_queue<Stu, vector<Stu>, greater<Stu> > c; //===============>这里是greater,就重写>
	
	for ( int i = 0; i < 5; ++i ) {
		Stu a = {i, "s"};
		c.push(a);
	}
	
	cout << "C:\n";
	while ( !c.empty() ) {
		cout << c.top().name << ' ' << c.top().age << endl;
		c.pop();
	}
	cout << endl << endl;
	
	Stu a = {10, "田小锋"}; c.push(a);
	Stu b = {10, "田小锋01"}; c.push(b);
	cout << "C:\n";
	while ( !c.empty() ) {
		cout << c.top().name << ' ' << c.top().age << endl;
		c.pop();
	}
	cout << endl;
	
	return 0;
}

下面是直接在结构体里面重写比较方法

#include <iostream>
#include <queue>
#include <string>
using namespace std;

//学生,假设年龄小的优先级高
//年龄相同,按姓名字典序
typedef struct Student{
	int age;
	string name;
	
	//b是队首元素
	bool operator > ( const Student b) const  //这个const不能少哦,
	{
		if (age == b.age) return b.name > name;//按字典序来看优先级
		return b.age < age;//年龄小的优先级高
	}
}Stu;


int main()
{
	priority_queue<Stu, vector<Stu>, greater<Stu> > c;
	
	for ( int i = 0; i < 5; ++i ) {
		Stu a = {i, "s"};
		c.push(a);
	}
	
	cout << "C:\n";
	while ( !c.empty() ) {
		cout << c.top().name << ' ' << c.top().age << endl;
		c.pop();
	}
	cout << endl << endl;
	
	Stu a = {10, "田小锋"}; c.push(a);
	Stu b = {10, "田小锋01"}; c.push(b);
	cout << "C:\n";
	while ( !c.empty() ) {
		cout << c.top().name << ' ' << c.top().age << endl;
		c.pop();
	}
	cout << endl;
	
	return 0;
}
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C++ STL中没有直接提供二叉搜索树的实现,但STL中有一些关于树的容器,比如set和map,它们底层的实现就是基于红黑树(一种平衡二叉搜索树)的。你可以使用这些容器来实现二叉搜索树的功能。关于二叉搜索树的一些知识,比如二叉树的遍历、迭代、线索二叉树、堆、Huffman编码、AVL树等都可以在STL中找到相应的实现。 二叉搜索树的查找可以通过比较根节点的值和目标值的大小来判断是往左子树还是往右子树查找,并重复这个过程直到找到目标值或者遍历到叶子节点为止。常规实现使用循环来实现查找,递归实现使用递归函数来查找。 二叉搜索树的插入操作也可以通过递归或循环来实现,根据目标值和当前节点的值的大小关系来决定是往左子树还是往右子树插入新节点。 STL中的二叉搜索树容器如set和map提供了插入、删除和查找等功能,并且保持了二叉搜索树的性质。你可以使用这些容器来处理二叉搜索树相关的操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [C++ STL 数据结构 树](https://download.csdn.net/download/xinxipan/3008948)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【C++ STL】-- 二叉搜索树](https://blog.csdn.net/weixin_64609308/article/details/128018280)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值