This page is still under construction.

Parts of this page are still being built. What you see may change.

Cow Politics

Interview

Time limit2sMemory limit128 MB

Summary
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 NN pastures (2≤N≤200,0002 \le N \le 200{,}000) numbered 1…N1 \dots N. Exactly N−1N - 1 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 ii is described by its parent PiP_i (0≤Pi≤N0 \le P_i \le N). The root pasture has parent Pi=0P_i = 0, meaning it has no parent.

The cows have organized KK political parties (1≤K≤N/21 \le K \le N/2) numbered 1…K1 \dots K. Every cow belongs to exactly one party; cow ii belongs to party AiA_i (1≤Ai≤K1 \le A_i \le K). 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 NN and KK.
  • Lines 2…N+12 \dots N+1: line i+1i + 1 contains two space-separated integers AiA_i and PiP_i, describing pasture ii.

Output

  • Lines 1…K1 \dots K: line ii contains a single integer, the range of party ii.

Examples2

  1. Example 1

    Input
    6 2
    1 3
    2 1
    1 0
    2 1
    2 1
    1 5
    
    Expected output
    3
    2
    
  2. Example 2

    Input
    2 1
    1 0
    1 1
    
    Expected output
    1