#SRD0000093. Đỉnh gần nhất (Nearest vertex)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Đỉnh gần nhất (Nearest vertex)
Nearest vertex
Source: MarisaOJ
Version: Phuoc Hung OJ Extended
Problem Statement
You are given an undirected tree with vertices, numbered from to . Vertex has an integer value . The distance between two vertices is the number of edges on their unique simple path.
Every query specifies a starting vertex and a value . Find the minimum distance from to any vertex labelled . A destination vertex can be reused for different queries. If no vertex carries value , print -1.
If the starting vertex itself has value , the answer is .
Input
- The first line contains .
- The second line contains integer values .
- The next lines each contain endpoints of an undirected tree edge.
- Each of the final lines contains a starting vertex and the target value .
Output
Print one line per query: the minimum number of edges to a matching vertex, or -1 if no matching vertex exists.
Subtasks
- Subtask 1 (10 points): , .
- Subtask 2 (20 points): , .
- Subtask 3 (30 points): , .
- Subtask 4 (40 points): , .
Complete conditions for all subtasks, subject to the tighter limits above: , , .
Examples
Input
3 2
1 2 3
1 2
1 3
2 2
1 3
Output
0
1
Explanation
The tree edges are and , and the values at vertices are . For query , vertex itself has the requested value, yielding 0. For query , the only vertex with value is vertex , one edge from vertex , yielding 1.