Under construction

Still being built. Things may change

Distance Sum Maximization

Time limit3sMemory limit1024 MB

Summary
Given a tree, answer each query (u, v) by finding the maximum of dist(x,u) + dist(x,v) over all vertices x.
Level

Medium7 of 10

Topics
Tree, Segment tree, DFS
Solved
No attempts yet

Problem

A tree with NN vertices (an undirected graph with no cycles that is connected) is given. The vertices are numbered from 11 to NN, and the edges are numbered from 11 to (N−1)(N-1).

Write a program that processes the following query.

  • uu vv: For a vertex xx (1≤x≤N1\le x\le N), print the maximum value of dist⁡(x,u)\operatorname{dist}(x,u) + dist⁡(x,v)\operatorname{dist}(x,v). (1≤u,v≤N1\le u,v\le N)

Here dist⁡(x,y)\operatorname{dist}(x,y) is the number of edges on the shortest path from vertex xx to vertex yy. For every vertex xx of the tree, dist⁡(x,x)=0\operatorname{dist}(x,x) = 0.

Input

The first line contains the number of vertices NN (2≤N≤300 0002\le N\le 300\,000).

Each of the next (N−1)(N-1) lines describes the tree. The ii-th line contains the two vertices connected by edge ii, separated by a space.

The next line contains the number of queries QQ (2≤Q≤300 0002\le Q\le 300\,000). Each of the following QQ lines contains one query.

Output

Print the answers to the QQ queries in order, one per line.

Examples1

  1. Example 1

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