Cow Politics
InterviewTime limit2sMemory limit128 MB
Given a tree with each node belonging to one of K parties, find the diameter (greatest distance between any two nodes) of the nodes in each party.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Divide and conquer, Dynamic programming
- Solved
- No attempts yet
Problem
Farmer John's cows live on pastures () numbered . Exactly bidirectional paths, each of unit length, connect the pastures so that every pasture is reachable from every other one. The pastures and paths therefore form a tree.
Each pasture is described by its parent (). The root pasture has parent , meaning it has no parent.
The cows have organized political parties () numbered . Every cow belongs to exactly one party; cow belongs to party (). Each party contains at least two cows.
The range of a party is the greatest distance between any two cows in that party, where the distance between two cows is the number of paths on the route connecting their pastures.
For example, suppose party 1 consists of cows 1, 3, and 6, party 2 consists of cows 2, 4, and 5, and the pastures are connected as shown below (party 1 members are marked with dashes):
-3-
|
-1-
/ | \
2 4 5
|
-6-
The greatest distance between two cows of party 1 is 3 (between cows 3 and 6), and the greatest distance for party 2 is 2 (for instance, between cows 2 and 4). So party 1 has range 3 and party 2 has range 2.
Determine the range of every party.
Input
- Line 1: two space-separated integers and .
- Lines : line contains two space-separated integers and , describing pasture .
Output
- Lines : line contains a single integer, the range of party .