PT07Z - Longest path in a tree

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.


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).


Print the length of the longest path on one line.


1 2
2 3


hide comments
bani_raheja: 2018-01-03 21:25:31

First did it in around september when I had no knowledge of DP, by using two BFS. Did it again with dp in January. Trust me, you'd love the DP idea. It's much more reliable than 2 BFSs.

aniket000: 2017-12-29 19:39:00

@diptark_bose , you can take node 1 as the starting node for the first dfs (used to calculate the farthest node) as it must be present in every test case , then use farthest node as the starting node for the second dfs.

aniket000: 2017-12-29 19:35:15

just calculate the diameter of the tree, diameter-1 is your longest path in the tree

diptark_bose: 2017-12-20 16:40:57

How to decide the initial starting node when doing the 2 bfs approach?

sambit95: 2017-12-17 20:19:47

I'm pretty sure there are test cases with 0<=U,V<=N when it says 1<=U,V<=N. faced SIGSEGV (Don't decrease the node no by 1)

g_o_d: 2017-12-16 07:15:43

AC in one go ! Used 1 dfs.

raveena_93: 2017-12-02 11:05:04

Applied 2 dfs as well as 2 bfs approach in java..TLE with both approach :(.. Can anyone suggest some optimization techniques as I have analysed memorization can't be applied in this case.

Omar: 2017-10-13 20:47:00

Run BFS on any node s in the graph, remembering the node u discovered last. Run BFS from u remembering the node v discovered last. d(u,v) is the diameter of the tree.
Just make sure to choose the right random node to avoid wrong answer.

mahilewets: 2017-09-12 11:54:10

It is very hard to not to AC first submission.

rvatna: 2017-09-11 15:57:23

#1. Test example on Spoj Toolkit is wrong, it's not even a tree since there is a cycle. Test on your own,
1 2
2 3
1 11
3 11
4 11
4 5
5 6
5 7
6 7
4 12
8 12
9 12
8 10
9 10
8 9

Last edit: 2017-09-11 15:57:56

Added by:Thanh-Vy Hua
Time limit:0.181s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ERL JS-RHINO NODEJS PERL6 VB.NET
Resource:Co-author Amber