Tree and queries 5
Time limit2sMemory limit512 MB
On a tree where vertices flip black and white, answer for each query the distance from a given vertex to the nearest white vertex.
- Level
Hard9 of 10
- Topics
- Tree, Divide and conquer, Dynamic programming, Shortest path
- Solved
- No attempts yet
Problem
You are given a tree with vertices. A tree is a connected undirected graph with no cycle. The vertices are numbered from 1 to , and the edges are numbered from 1 to . Every vertex is black at the start.
Write a program that handles the two query types below.
1 i: flip the color of vertex . Black becomes white, and white becomes black.2 v: among all white vertices , print the smallest distance from to . Here and may be the same vertex, so the answer is 0 when is white. If the tree has no white vertex, print -1.
The distance between two vertices is the number of edges on the path that joins them.
Input
The first line contains the number of vertices ().
Each of the next lines contains the two vertex numbers and joined by edge ().
The next line contains the number of queries ().
Each of the next lines contains one query, written as 1 i or 2 v, with .
Output
For each query of type 2, print the answer on its own line, in the order the queries are given.