PAT-A 1147 Heaps(30 分)

本文介绍了一个使用C++实现的程序,该程序能够根据输入的数据判断是否构成最大堆或最小堆,并通过后序遍历的方式打印出堆的内容。涉及到的数据结构包括数组表示的完全二叉树和堆。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstdio>
using namespace std;
#define MAXN 1026

int isempty=0;


void postorder(int n,int heap[],int head){
    if(head<n){
        postorder(n,heap,head*2+1);
        postorder(n,heap,head*2+2);
        if(!isempty){
            printf("%d",heap[head]);
            isempty=1;
        }else{
            printf(" %d",heap[head]);
        }
    }
}
int main()
{
    int M,n,heap[MAXN];
    scanf("%d %d",&M,&n);
    while(M--){
        isempty=0;
        for(int i=0;i<n;i++){
            scanf("%d",&heap[i]);
        }
        int flag=heap[0]>heap[1]?1:-1;
        for(int j=0;2*j+1<n;j++){
            int l=2*j+1;
            int r=2*j+2;
            if(flag==1&&(heap[j] < heap[l] || (r<n  &&  heap[j] < heap[r]))){
                flag=0;
                break;
            }else if(flag == -1 && (heap[j] > heap[l] || (r<n  && heap[j] > heap[r]))){
                flag=0;
                break;
            }
        }
        if (flag == 0) printf("Not Heap\n");
        else printf("%s Heap\n", flag == 1 ? "Max" : "Min");
        postorder(n,heap,0);
        printf("\n");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值