1 Star 0 Fork 0

Jelly-Aries / pastebin

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
left_sided_tree.cpp 1.72 KB
一键复制 编辑 原始数据 按行查看 历史
Jelly-Aries 提交于 2019-07-26 08:52 +08:00 . Upload left_sided_tree.cpp
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
struct Heap
{
Heap *lson, *rson;
int dist, val;
Heap()
{
lson = rson = NULL;
dist =val = 0;
}
}*root = NULL;
void set_dist(Heap *node)
{
if (node->rson != NULL)
node->dist = node->rson->dist + 1;
else node->dist = 0;
}
Heap *merge(Heap *a, Heap *b)
{
//一个节点是空的,那么返回另一个节点
if (a == NULL) return b;
else if (b == NULL) return a;
//将权值较小的作为根结点
if (a->val > b->val) swap(a, b);
//合并右儿子和大权值节点
a->rson = merge(a->rson, b);
if (a->rson != NULL && a->lson != NULL)
{
if (a->lson->dist < a->rson->dist)
swap(a->lson, a->rson);
}
else if (a->lson == NULL && a->rson != NULL)
swap(a->lson, a->rson);
set_dist(a);
return a;
}
void Insert(int val)
{
//必须先特判堆是空的结果
if (root == NULL)
{
root = new Heap();
root->val = val;
set_dist(root);
return ;
}
Heap *num = new Heap();
num->val = val;
set_dist(num);
root = merge(root, num);
}
int Top()
{
if (root != NULL)
return root->val;
else return 0; //rand();
}
void Pop()
{
Heap *temp = root;
root = merge(root->lson, root->rson);
delete(temp);
}
int main()
{
int n, opt, val;
cin >> n;
while (n--)
{
cin>>opt;
switch (opt)
{
case 1:cin>>val;Insert(val);break;
case 2:cout<<Top()<<endl;break;
case 3:Pop();break;
default:break;
}
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Jelly-Goat/pastebin.git
git@gitee.com:Jelly-Goat/pastebin.git
Jelly-Goat
pastebin
pastebin
master

搜索帮助