2022-5-16 小明喜欢树

小明喜欢树

题目

小明很喜欢树,现在小明得到一棵树,现在小明想知道树的每一层的节点权值最大值是多少,聪明的你可以可以帮助小明解决这个问题吗。

输入

第一行输入一个整数n(1 <= n <= 100000) 接下来n行,每行有两个整数,对于第i行,表示编号为i的节点的父节点编号(没有父节点编号为0)以及编号为i的节点的权值(1<=权值<=1e9,1为根节点)。

输出

输出每一层的最大节点编号是几,每两个数字之间用空格隔开。

输入样例

6
0 1
1 3
1 2
3 5
3 3
2 9

输出样例

1 3 9

代码

#include<bits/stdc++.h>

#define N 100005
using namespace std;

struct Node {
    int val;
    vector<Node *> children;

    Node(int val) : val(val), children(0) {}
};

Node *nodeList[N]{nullptr};

int main() {
    int n;
    cin >> n;
    nodeList[0] = new Node(0);
    for (int i = 1, parent, value; i <= n; i++) {
        cin >> parent >> value;
        nodeList[i] = new Node(value);
        nodeList[parent]->children.push_back(nodeList[i]);
    }
    queue<Node *> que;
    que.push(nodeList[0]);
    vector<int> result;
    while (!que.empty()) {
        int size = que.size(), maxLine = 0;
        while (size--) {
            auto cur = que.front();
            que.pop();
            maxLine = max(maxLine, cur->val);
            for (int i = 0; i < cur->children.size(); i++) {
                que.push(cur->children[i]);
            }
        }
        result.push_back(maxLine);
    }
    for (int i = 1; i < result.size(); i++) {
        cout << result[i];
        if (i + 1 != result.size()) cout << ' ';
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值