Circumcenter of a Tree
Time limit2sMemory limit512 MB
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.
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 . () The tree consists of vertex 1, vertex 2, ..., vertex .
From the second line to the -th line, two positive integers and representing the edge information of the tree are given, separated by a space. This means that vertex and vertex are connected. (, )
The given connections form a tree.
The -th line gives the number of queries . ()
Over the next lines, three positive integers , , representing the three vertices that define the circumcenter are given, separated by spaces. ()
Output
For each query over 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.