Colorful Tree

3.8

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

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

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

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

Input format

  • First line: Two integers N and M
  • Next line: N space-separated integers, where the ith integer is Ci denoting the color of the ith node
  • Next N1 lines: Two integers U and V representing an edge between nodes U and V
  • Next M lines: Two integers K and C

Output format

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

Input Constraints

1N,M5×105

1Ci5×105

1U,VN

1KN

1C5×105

Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

 

Tree Corresponding to the Sample
The tree corresponding to the input

 

Editor Image

?