二叉树--堆的实现

题目: Heapsort implementation(堆实现)

总Time Limit: 
3000ms 
Memory Limit: 
65535kB
Description

Given a Array, initially empty, with twokinds of operations:

1. Add an element, insert a new elementinto the array.

2. Output and delete the smallest number inthe array.

Use heap to implement a efficient algorithmwith functions above.

Input
The first line is an integer t, which represents the number of groups of the test data.
For each group data, the first line is an integer n. n represents the number of operations.
First of each operation there is an integer ‘type’. 
When type=1, it means an adding operation, followed by an integer u, which represent the element to be inserted. 
When type=2, it means a deleting operation, output and delete the smallest element in the array.
1<=n<=100000.
Output
Output the number deleted in each operation.
Sample Input
251 11 21 32241 51 11 72
Sample Output
121
分析:用数组模拟堆的元素插入和删除堆顶值。
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

const int maxn = 100005;
int m,n,size;
int val[maxn];

//新插入元素从堆顶往上放到合适位置
void up()
{
	int tmp = size,valInsert = val[size],parx = size/2;
	while((val[parx] > valInsert) && (parx >= 1)) {
	    val[tmp] = val[parx];
	    tmp = parx;
	    parx = tmp/2;
	}
	val[tmp] = valInsert;
}

//删除堆顶元素
void down()
{
	val[1] = val[size--];//删除堆顶元素
	int tmp = 1,valDown = val[1],y = 2;
	while(y <= size) {
	    if(val[y] > val[y+1]) y++;//找到子节点中最小值
	    if (val[y] < valDown)
	    {
	    	val[tmp] = val[y];
	    	tmp = y;
	    	y = 2*tmp;
	    }else break;
	}
	val[tmp] = valDown;
}

void insert(int b)
{
	val[++size] = b;
	up();
}

void del()
{
	if(size == 0) return;
	else printf("%d\n",val[1]);
	down();
}

int main()
{
	cin >> m;
	while(m--) {
	    cin >> n;
	    memset(val,0,sizeof(val));
	    //如果这里不初始化,需要在判断子节点最小值时加上y<=size或y+1<=size
	    size = 0;
	    while(n--) {
	    	int a,b;
	        cin >> a;
	        if(a == 1) {cin >> b;insert(b);}
	        else del();
	    }
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值