二叉树--堆的实现
来源:互联网 发布:网络推广代运营公司 编辑:程序博客网 时间:2024/05/17 18:03
题目: 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;}
阅读全文