2450 Problem B 树的高度

389 篇文章 1 订阅
144 篇文章 2 订阅

问题 B: 树的高度
时间限制: 1 Sec 内存限制: 128 MB
献花: 43 解决: 24
[献花][花圈][TK题库]
题目描述
一棵树有n个节点,其中1号节点为根节点。

输入
第一行是整数n,表示节点数

后面若干行,每行两个整数a b,表示b是a的子节点。

输出
求这棵树的高度(根节点为第1层)

样例输入
5
1 2
1 3
3 4
3 5
样例输出
3

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>

using namespace std;
const int MaxN = 1000010;
typedef struct Tnode
{
    vector<int>child;
    bool NeedClear;
    int level;
}TNode;

TNode Tree[MaxN];

int Deepth(int root)
{
    int dp = 0;
    queue <int> que;
    que.push(root);

    while(que.size())
    {
        int node = que.front();
        que.pop();

        for(int i=0;i<Tree[node].child.size();++i)
        {
            int childid = Tree[node].child[i];
            Tree[childid].level = Tree[node].level + 1;
            Tree[childid].NeedClear = true;
            que.push(childid);

            if(Tree[childid].level > dp)
                dp = Tree[childid].level;
        }
    }

    return dp;
}

int main()
{
#ifdef _Debug
freopen("data.txt","r+",stdin);
#endif

    std::ios::sync_with_stdio(false);

    int n,root,child;


    while(cin >> n)
    {
        for(int i=0;i<n-1;++i)
        {
            cin >> root >> child;
            if(Tree[root].NeedClear)
                Tree[root].child.clear();
            Tree[root].child.push_back(child);
        }
        Tree[1].level = 1;
        cout << Deepth(1)<<endl;
    }

    return 0;
}

/**************************************************************
    Problem: 2450
    User: Sharwen
    Language: C++
    Result: 升仙
    Time:177 ms
    Memory:32960 kb
****************************************************************/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值