# 数据结构-Heap(堆)

### #1105 : 题外话·堆

#### 输出

5
A 77751
A 1329
A 26239
A 80317
T


80317

1.取最大值，并删除它。

2，在树种插入一个数。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000 + 10;
int N;
struct node{
int value;
int L, R;
node(){
L = 0;
R = 0;
}
};
class Heap{
public:
Heap()
{
root = 0;
cnt = 0;
}
void insert(int value)//插入一个值
{
if(root == 0)//空树
{
root = ++cnt;
Tree[root].value = value;
Tree[root].L = 0;
Tree[root].R = 0;
}
else
{
int father = cnt>>1;
if(Tree[father].R == 0 && father)
{
Tree[father].R = ++cnt;
Tree[cnt].L = 0;
Tree[cnt].R = 0;
Tree[cnt].value = value;
}
else
{
father++;
Tree[father].L = ++cnt;
Tree[cnt].L = 0;
Tree[cnt].R = 0;
Tree[cnt].value = value;
}
}
}
void update_up(int id)//丛编号为id的节点开始向上调整，使得整棵树满足大根堆的性质
{
int father = id>>1;
if(father == 0) return;
if(Tree[father].value < Tree[id].value)
{
int temp = Tree[father].value;
Tree[father].value = Tree[id].value;
Tree[id].value = temp;
update_up(father);
}
else return;
}
int getRoot()//获取整棵树的根，也就是最大值
{
int temp = Tree[root].value;
Tree[root].value = Tree[cnt].value;
int father = cnt>>1;
if(cnt == Tree[father].L) Tree[father].L = 0;
else Tree[father].R = 0;
cnt--;
return temp;
}
void update_down(int id)//从根往下更新,直到整棵树满足大根堆性质
{
int lson = Tree[id].L;
int rson = Tree[id].R;
if(lson == 0 && rson == 0) return;
if(rson == 0)
{
if(Tree[id].value < Tree[lson].value)
{
int temp = Tree[id].value;
Tree[id].value = Tree[lson].value;
Tree[lson].value = temp;
update_down(lson);
return;
}
else return;
}
if(Tree[lson].value >= Tree[rson].value)
{
if(Tree[id].value >= Tree[lson].value) return;
int temp = Tree[id].value;
Tree[id].value = Tree[lson].value;
Tree[lson].value = temp;
update_down(lson);
return;
}
else
{
if(Tree[id].value >= Tree[rson].value) return;
int temp = Tree[id].value;
Tree[id].value = Tree[rson].value;
Tree[rson].value = temp;
update_down(rson);
return;
}
}
node Tree[maxn];
int root;//树根
int cnt;
};
int main()
{
scanf("%d", &N);
Heap x;
char op[10];
for(int i = 1; i <= N; i++)
{
scanf("%s", op);
if(op[0] == 'T')
{
printf("%d\n", x.getRoot());
x.update_down(x.root);
}
else
{
int value;
scanf("%d", &value);
x.insert(value);
x.update_up(x.cnt);
}
}
return 0;
}