Skip to main content
Tuesday (24.11.2026) at 20:00: ALGOR Contest: Round #4 (Special Challenge) starts!

~/algor $ cat problems/daraxt-masofa-sorovlari

Distance queries in a tree

Hard 2000 ms 128 MB 95%
Share

A tree with $n$ vertices numbered from $1$ to $n$ is given; every edge has length $1$. $q$ queries arrive: each gives two vertices $u$ and $v$; find the distance between them — the number of edges on the path joining them.

A tree: the unique path between the two queried vertices is highlighted

Input

The first line contains a positive integer $n$. Each of the next $n - 1$ lines contains two positive integers: $u$ and $v$ — an edge. The next line contains a positive integer $q$, and each of the next $q$ lines contains two positive integers: $u$ and $v$ — a query.

Output

$q$ lines — the answers to the queries.

Note

$1 \le n, q \le 5 * 10^{4}$
$1 \le u, v \le n$
The given edges form a tree.

Examples

Input #1
7
1 2
1 3
2 4
2 5
3 6
6 7
3
4 5
4 7
6 6
Output #1
2
5
0
Input #2
1
1
1 1
Output #2
0

Sign in to submit a solution

Signing up is free and takes a minute.