zoukankan      html  css  js  c++  java
  • 二叉树——实现堆结构

    题目链接
    总时间限制: 3000ms 内存限制: 65535kB
    描述
    定义一个数组,初始化为空。在数组上执行两种操作:

    1、增添1个元素,把1个新的元素放入数组。

    2、输出并删除数组中最小的数。

    使用堆结构实现上述功能的高效算法。

    输入
    第一行输入一个整数t,代表测试数据的组数。
    对于每组测试数据,第一行输入一个整数n,代表操作的次数。
    每次操作首先输入一个整数type。
    当type=1,增添操作,接着输入一个整数u,代表要插入的元素。
    当type=2,输出删除操作,输出并删除数组中最小的元素。
    1<=n<=100000。
    输出
    每次删除操作输出被删除的数字。
    样例输入

    2
    5
    1 1
    1 2
    1 3
    2
    2
    4
    1 5
    1 1
    1 7
    2
    

    样例输出

    1
    2
    1
    

    提示
    每组测试数据的复杂度为O(nlgn)的算法才能通过本次,否则会返回TLE(超时)
    需要使用最小堆结构来实现本题的算法

    #include <cstdio>
    #include <cstdlib>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int heap[100010];
    int len;
    //int maxsize;
    
    
    void Init(){
        //maxsize = 0;
        len = 0;
    }
    
    void Insert(int x){
        //heap[len] = x;
        len++;
    
        int i = len -1;
    
        while(i > 0){
            int j = (i-1)/2;
            if(x > heap[j])
                break;
            heap[i] = heap[j];
            i = j;
        }
        heap[i] = x;
    }
    
    int Del(){
        if(0 == len){
            exit(1);
        }
    
        int temp = heap[0];
        len--;
    
        if(0 == len){
            return temp;
        }
    
        int x = heap[len];
        int i = 0;
        int j = 2*i+1;
        while(j <= len-1){
            if((j < len-1)&& (heap[j] > heap[j+1])){
                j++;
            }
            if(x < heap[j]){
                break;
            }
            heap[i] = heap[j];
            i = j;
            j = 2*i+1;
        }
        heap[i] = x;
        return temp;
    }
    
    int main(){
        //freopen("in.txt","r",stdin);
        int t,n,type,x;
        scanf("%d",&t);
        while(t--){
            scanf("%d",&n);
            //struct node p;
            Init();
            while(n--){
                scanf("%d",&type);
                if(type == 1){
                    scanf("%d",&x);
                    Insert(x);
                }
                else if(type == 2)
                    printf("%d
    ",Del());
            }
        }
        return 0;
    }
    
  • 相关阅读:
    ie条件注释
    css3之图片一闪而过特效
    css帧动画之图片发亮
    css3动画
    解决ie6不兼容透明图片
    jquery实现拖拽的效果
    原生js实现拖拽弹框的效果
    C++学习笔记十之连接数据库
    C++学习笔记九之异常处理
    C++学习笔记八之STL内置算法
  • 原文地址:https://www.cnblogs.com/sean10/p/4987483.html
Copyright © 2011-2022 走看看