SPOJ - PT07Z (DFS)

传送门 

题面:

You are given an unweighted, undirected tree. Write a program to output the length of the longest path

(from one node to another) in that tree. The length of a path in this case is number of edges we traverse from source to destination.

Input

The first line of the input file contains one integer N --- number of nodes in the tree (0 < N <= 10000). Next N-1 lines contain N-1 edges of that tree --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u, v <= N).

Output

Print the length of the longest path on one line.

Example

Input:
3
1 2
2 3

Output:
2

 题目大意就是给你一棵无权值,无向的树,求它的最长路径。

思路就是用vector储存树,然后由无向树的性质可从任意一个点进行一次DFS,在DFS的过程中记录从该节点出发的路径的最长值并返回,由于最长路径可能不会经过出发结点,于是在对每一个点进行DFS时记录子路径的最长值和次长值并与当前最长路径比较,即可得出结果。

#include <vector>
#include <stdio.h>
using namespace std;
int ans = 0;
vector <int > vec[10010];

int DFS(int node,int fa)
{
    int L = vec[node].size() , MAx = 0 , MAx1 = 0;
    for(int i = 0 ; i < L ; ++i)
    {
        if(vec[node][i] == fa) continue; //不可回退。
        int t = DFS(vec[node][i],node);
        if(t > MAx) MAx1 = MAx , MAx = t;
        else if(t > MAx1) MAx1 = t;
    }
    if(MAx + MAx1 + 1 > ans) ans = MAx + MAx1 + 1;
    return MAx + 1;
}

int main()
{
    int n,a,b;
    scanf("%d",&n);
    for(int i = 0 ; i < n - 1 ; ++i)
    {
        scanf("%d%d",&a,&b);
        vec[a].push_back(b);
        vec[b].push_back(a);
    }
    DFS(1,n+1);
    printf("%d\n",ans - 1); //最多经过节点数减1即为最长路径的长度。
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值