Little Shino and K Ancestor

3.9

19 votes
Algorithms, Depth First Search, Easy, Graphs
Problem

Assume that you are given an undirected rooted tree with N nodes and an integer K. Node 1 is the root of the tree. Each node is uniquely numbered from 1 to N. Additionally, each node also has a color and the color is an integer value.

Note: Different nodes can have the same color.

For each node, you are required to find the Kth closest ancestor from that node which has the same color.

enter image description here

Input Format:
The first line consists of two integers, denoting N and K (1N,K106). The second line is an array A of length N, represented as space separated integers. Here Ai (1Ai106) is the color-value of ith node in the tree. This is followed by N1 lines comprising of two space separated integers x and y, which denotes that there is an edge between nodes that are numbered x and y.

Output Format:
Print N space separated integers, where ith integer denotes the Kth closest ancestor from ith node which has the same color. If no such ancestor exists, print 1.

Time Limit: 2
Memory Limit: 512
Source Limit:
Explanation

Node 1, 3 and 5 do not have any ancestor with the same color. Node 2 has only one ancestor (Node 1) with the same color. Node 4 has two ancestors (Node 1 and Node 2) with the same color. For node 4, the 2nd closest ancestor is 1.

Editor Image

?