Longest Paths in Tree

4.8

10 votes
Algorithms, Approved, Graphs, Medium
Problem

You are given a tree. Simple path of length m is a sequence of vertices v1,v2,,vm such that

  • All vi are distinct.
  • vi and vi+1 are connected by edge for 1im1.

For each vertex find length of longest simple path that goes through this vertex. Also count number of this paths. Two paths considered distinct if set of vertices of this paths differ.

Input Format:
First line of input contains single positive integer n -- number of vertices of the tree.
Next n1 lines contains pairs space-separated integers ui,vi -- edges of the tree.

Output Format:
Output n lines. i-th line must contain two integers -- length of the longest simple path containing vertex i and number of such paths.

Constraints:
1n300,000.

Scoring:
50 points
Additionally n3,000.
50 points
No additional constraints.

Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

Longest paths going through vertex 1: (1,2,3), (1,2,4).
Longest paths going through vertex 2: (1,2,3), (1,2,4), (3,2,4).
Cases of vertices 3 and 4 are similar to vertex 1.

Editor Image

?