1155 Heap Paths (30 point(s))

思路:

叶子节点从右到左,入栈到根节点的路径,出栈输出。

1155 Heap Paths (30 point(s))

In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: if P is a parent node of C, then the key (the value) of P is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of C. A common implementation of a heap is the binary heap, in which the tree is a complete binary tree. (Quoted from Wikipedia at https://en.wikipedia.org/wiki/Heap_(data_structure))

One thing for sure is that all the keys along any path from the root to a leaf in a max/min heap must be in non-increasing/non-decreasing order.

Your job is to check every path in a given complete binary tree, in order to tell if it is a heap or not.

Example:

#include<iostream>
#include<vector>
#include<cmath>
#include<set>
using namespace std;

set<string> heap;

void Print(vector<int> &Tree, int begin, int end)
{
    vector<int> Seq;
    for(int i = begin; i > end; i--) {
        int last = Tree[i];
        for(int k = i; k >= 1; k /= 2) {
            Seq.push_back(Tree[k]);
            int diff = Tree[k] - last;
            last = Tree[k];
            if(diff > 0) heap.insert("Max Heap");
            else if(diff < 0) heap.insert("Min Heap");
        }
        for(auto x = Seq.rbegin(); x != Seq.rend(); x++) cout << (x == Seq.rbegin()? "" : " ") << *x;
        cout << "\n";
        Seq.clear();
    }
}

int main()
{
    int N;
    cin >> N;
    vector<int> Tree(N+1);
    int right = pow(2, (int)log2(N)) - 1;
    for(int i = 1; i <= N; i++) cin >> Tree[i];
    Print(Tree, right, N/2); 
    Print(Tree, N, right); 
    if(heap.size() != 1) cout << "Not Heap";
    else cout << *heap.begin();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值