二叉树--堆的实现

来源:互联网 发布:网络推广代运营公司 编辑:程序博客网 时间: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;}



阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 茶叶 购买 卖茶叶怎么样 新买茶壶 茶壶买什么牌子好 茶壶在哪里买 买紫砂茶壶 新买的茶壶怎么样开壶 荷叶减肥茶哪里买 买普洱茶去哪 买茶叶去哪个网 在网上买茶 哪个网买茶叶好 茶怎么买 买茶的网站 买茶叶上什么网 买买茶怎么样 和茶网 买茶网网址 茶购网 点茶网 网茶网 引茶网网址 第一茶网 买茶网的茶叶怎么样 卖茶网站 茶叶销售 茶叶购买 买草莓 草莓苗在哪里买 那里有草莓苗买 买草莓遇美丽陷阱 哪里可以买草莓苗 哪里买荔枝干 买荔枝 卖荔枝 买打胎药 网上怎么买打胎药 网上买打胎药 网上买减肥药靠谱吗 避孕药怎么买 瑶药哪里买