On a tree where vertices flip black and white, answer for each query the distance from a given vertex to the nearest white vertex.
Hard9TreeDivide and conquerDynamic programmingShortest pathNo attempts yetTime limit2sMemory limit512 MB
Description
Examples2
Problem
You are given a tree with N vertices. A tree is a connected undirected graph with no cycle. The vertices are numbered from 1 to N, and the edges are numbered from 1 to N−1. Every vertex is black at the start.
Write a program that handles the two query types below.
1 i: flip the color of vertex i. Black becomes white, and white becomes black.
2 v: among all white vertices u, print the smallest distance from u to v. Here u and v may be the same vertex, so the answer is 0 when v 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 N (2≤N≤100000).
Each of the next N−1 lines contains the two vertex numbers u and v joined by edge i (1≤u,v≤N).
The next line contains the number of queries M (1≤M≤100000).
Each of the next M lines contains one query, written as 1 i or 2 v, with 1≤i,v≤N.
Output
For each query of type 2, print the answer on its own line, in the order the queries are given.