51Nod 2282 树的深度 c/c++题解

题目描述

给出一棵n个节点的树,节点编号为1-n(根节点编号为1,且根节点深度为1),求这棵树的深度(树中节点的最大层次)。
例如:
1─2─4─5
└─3
其中1-2-4-5这条边是最长的,所以树的深度为4。
输入
第一行:1个数n(1 < n <= 1000),表示树的节点数量。
后面n-1行:每行2个数x y,表示节点x是节点y的父节点(1 <= x, y <= n)。
输出
输出1个数,表示这棵树的深度
输入样例
5
1 2
1 3
2 4
4 5
输出样例
4

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n;
vector <int> edge[MAX];

int maxDepth = 1;
void dfs(int id,int depth)
{
    //cout << id << endl;
    if(depth > maxDepth)
    {
        maxDepth = depth;
    }
    for(int i = 0; i < (int)edge[id].size(); i++)
    {
        dfs(edge[id][i],depth+1);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    while(cin >> n)
    {
        int x,y;
        for(int i = 0; i < n-1; i++)
        {
            cin >> x >> y;
            edge[x].push_back(y);
        }
        maxDepth = 1;
        dfs(1,1);
        cout << maxDepth << endl;
    }

    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值