Under construction

Still being built. Things may change

Circumcenter of a Tree

Time limit2sMemory limit512 MB

Summary
Given a tree and many triples of vertices, for each triple report the unique vertex equidistant from all three (with equal distances as small as possible) or -1 if none exists.
Level

Hard8 of 10

Topics
Tree, Graph, BFS, Math
Solved
No attempts yet

Problem

Donggwan, absorbed in algorithms and now fixated on trees, wants to define a circumcenter in a tree. A tree is a connected graph with no cycles. But Donggwan realized that defining a circumcenter in a tree requires first defining "the distance between two vertices in a tree."

In a tree, the distance between two vertices is defined as the minimum number of edges that must be traversed to get from one vertex to the other. For three vertices of a tree, the circumcenter of the tree is defined as a vertex whose distances to the three vertices are all equal and as small as possible, if such a vertex exists. Mathematically, one can show that for three vertices of a tree, the circumcenter is unique if it exists.

It is obvious that changing the three vertices that define the circumcenter changes the circumcenter even for the same tree. Donggwan wants to find many different circumcenters but finds coding a nuisance. Write the code for Donggwan.

Input

The first line gives the number of vertices NN. (1≤N≤100,0001 \le N \le 100{,}000) The tree consists of vertex 1, vertex 2, ..., vertex NN.

From the second line to the NN-th line, two positive integers XX and YY representing the edge information of the tree are given, separated by a space. This means that vertex XX and vertex YY are connected. (1≤X,Y≤N1 \le X, Y \le N, X≠YX \neq Y)

The given connections form a tree.

The N+1N+1-th line gives the number of queries QQ. (1≤Q≤100,0001 \le Q \le 100{,}000)

Over the next QQ lines, three positive integers AA, BB, CC representing the three vertices that define the circumcenter are given, separated by spaces. (1≤A,B,C≤N1 \le A, B, C \le N)

Output

For each query over QQ lines, output the vertex number of the circumcenter if the circumcenter of the tree for the three given vertices exists, or -1 if it does not.

Examples3

  1. Example 1

    Input
    4
    1 2
    1 3
    1 4
    2
    2 3 4
    1 2 3
    
    Expected output
    1
    -1
    
  2. Example 2

    Input
    2
    1 2
    2
    1 1 2
    2 2 2
    
    Expected output
    -1
    2
    
  3. Example 3

    Input
    6
    1 2
    2 3
    2 4
    3 5
    5 6
    1
    1 4 6
    
    Expected output
    3