数据结构学习 -- 左偏树

1 篇文章 0 订阅
1 篇文章 0 订阅

虽然标题写得好像很叼的样子可是实际上就是放个模板=.=

左偏树顾名思义就是左边往左边偏的树,是一种可并堆。合并时尽量合并右子树以尽可能保持树的优美。

代码如下:(由于我用的Sublime貌似用中文写注释发上来是乱码)PS:一大堆是废话,核心其实就是Join函数

/* 
* @Author: 逸闲
* @Date:   2015-10-21 18:48:22
* @Last Modified by:   逸闲
* @Last Modified time: 2015-10-21 19:16:08
*/

#include "cstdio"
#include "cstdlib"
#include "iostream"
#include "algorithm"
#include "cstring"
#include "queue"

using namespace std;

#define INF 0x3F3F3F3F
#define MAX_SIZE 
#define Eps 
#define Mod 
#define Get_Distance(x) (x ? x -> Distance : 0)
#define Get_Size(x) (x ? x -> Size : 0)

inline int Get_Int()
{
	int Num = 0;
	char ch;
	do
		ch = getchar();
	while(ch < '0' || ch > '9');
	do
	{
		Num = Num * 10 + ch - '0';
		ch = getchar();
	}
	while(ch >= '0' && ch <= '9');
	return Num;
}

class DATA
{
public:
	int a;

	inline bool operator < (DATA const &b) const
	{
		return a < b.a;
	}
};

class Node
{
public:
	Node *Child[2], *Father;
	int Distance, Size; // The Distance is defined as the distance to the nearest leaf node(which may be empty) // Exactly the Distance of the node is 1 which hasn't rightchild
	DATA Value;
};

class Leftist_Tree
{
public:

	Node *Root;

	inline Node* New(DATA Value) // Create a new node
	{
		Node *x = (Node*)malloc(sizeof(Node));
		memset(x, 0, sizeof(Node));
		x -> Value = Value;
		x -> Size = x -> Distance = 1;
		return x;
	}

	Node* Join(Node *x, Node *y) // Merge two heap
	{
		if(!x)
			return y;
		if(!y)
			return x;
		if(y -> Value < x -> Value) // To satisfy the property of heap
			swap(x, y);
		x -> Child[1] = Join(x -> Child[1], y);
		x -> Child[1] -> Father = x;
		if(Get_Distance(x -> Child[1]) > Get_Distance(x -> Child[0])) // The leftchild should be "longer"
			swap(x -> Child[1], x -> Child[0]);
		x -> Size = Get_Size(x -> Child[0]) + Get_Size(x -> Child[1]);
		x -> Distance = Get_Distance(x -> Child[1]) + 1;
		return x;
	}

	inline void Join(Leftist_Tree *x)
	{
		Root = Join(Root, x -> Root);
		free(x);
	}

	inline void Push(DATA Value)
	{
		Node *x = New(Value);
		Root = Join(Root, x);
	}

	inline DATA Front()
	{
		return Root -> Value;
	}

	inline int Size()
	{
		return Root -> Size;
	}

	inline bool Empty()
	{
		return (Root == NULL);
	}

	inline void Pop()
	{
		Node *x = Root;
		Root = Join(Root -> Child[0], Root -> Child[1]);
		free(x);
	}
};

int N;

int main()
{
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
	fclose(stdin);
	fclose(stdout);
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值