zoukankan      html  css  js  c++  java
  • PAT A1147 Heaps [二叉堆]

    题目描述

    链接
    给一个树的层序遍历,判断它是不是堆,是大顶堆还是小顶堆。输出这个树的后序遍历

    分析

    • 堆实际是一棵完全二叉树,大顶堆满足,根节点大于左右子树的所有结点
    • 堆有数组存储,遍历堆的方法:遍历所有有孩子的结点,一共有(0)((n-1)/2)个。具体见代码!!注意不要越界!!
    #include<bits/stdc++.h>
    using namespace std;
    
    const int maxn = 105;
    int t,n,flag;
    int a[maxn];
    
    vector<int> ans;
    void postorder(int root){
        if(root >= n) return;
        postorder(2*root+1);
        postorder(2*root+2);
        ans.push_back(a[root]);
    }
    
    int main(){
        cin>>t>>n;
        while(t--){
            ans.clear();
            flag = 0;
            for(int i=0;i<n;i++) cin>>a[i];
            if(a[0] > a[1]) flag = 1; else if(a[0] < a[1]) flag = -1;
            for(int i=0;i<=(n-1)/2;i++){   //遍历堆!!
                int l = 2*i+1, r =2*i+2; //取孩子结点
                if(flag==1  &&  ( (a[i] < a[l]) || (r < n && a[i] < a[r]) ) ) flag = 0;  //r<n避免越界
                if(flag==-1 &&  ( (a[i] > a[l]) || (r < n && a[i] > a[r]) ) ) flag = 0;
            }
            postorder(0);
            if(flag==0) printf("Not Heap
    ");
            else if(flag == 1) printf("Max Heap
    ");
            else printf("Min Heap
    ");
    
            for(int i=0;i<n;i++){
                if(i==0) printf("%d",ans[i]);
                else printf(" %d",ans[i]);
            }
            printf("
    ");
        }
    }
    
    
  • 相关阅读:
    洛谷 P2053 :[SCOI2007]修车(拆点+最小费用流)
    LightOJ
    spark简单入门
    crontab 应用
    HttpClient的使用
    build.sbt的定义格式
    Scalatra
    SBT 构建scala eclipse开发
    mysql 存在更新,不存在插入
    Flash Vector例子
  • 原文地址:https://www.cnblogs.com/doragd/p/11291052.html
Copyright © 2011-2022 走看看