Colorful Tree

3.8

5 votes
Algorithms, Binary Search, Depth First Search, Graphs, Hard, Sqrt-Decomposition
Problem

You are given a tree that contains  nodes, where every node  is colored with some color .

The distance of a node from a node is defined as the number of edges along the simple path from the node  to the node . Your task is to answer queries of the following type:

  •  : Determine the distance of most distant node of color from node . If there is no node of color in the tree, then print .

Input format

  • First line: Two integers and
  • Next line:  space-separated integers, where the integer is  denoting the color of the node
  • Next  lines: Two integers  and  representing an edge between nodes and
  • Next lines: Two integers and

Output format

For each query, print the distance of most distant node of color from the node .
The answer for each query should come in a new line.

Input Constraints

Sample Input
10 15
2 6 5 99 500000 6 5 3 5 5
1 2
2 10
1 3
3 5
3 6
6 7
1 4
4 8
4 9
3 5
4 5
2 5
6 5
8 500000
5 500000
5 1000
6 6
8 6
5 99
3 6
3 100
9 5
7 5
3 3
Sample Output
3
4
4
4
4
0
-1
3
4
3
2
-1
5
5
3
Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

 

Tree Corresponding to the Sample
The tree corresponding to the input

 

Editor Image

?