Travelling in a tree

All submissions for this problem are available.
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
Leha likes traveling a lot. In particular he likes discovering new routes in his world which he calls a treeworld.
Leha's world is a connected tree of N vertices, so there is a unique path between any pair of vertices a and b. Every day Leha chooses some new pair of vertices and walks along this route. Sometimes he notices that he has already been in some vertices during his previous walks. So now for each new route that he takes, he is interested in knowing how many previous routes does it intersect? Two routes are considered to be intersecting with each other, if they have at least one common vertex.
Input
The first line contains one integer N denoting the number of vertices in the tree. Vertices are enumerated from 1 to N.
The following N1 describe the edges of the tree. Each of these lines contains two space separated integers u, v denoting that there is an edge between vertex u and v.
The next line contains an integer Q denoting the number of days Leha is traveling. Each of next Q lines contains two space separated integers u, v denoting the start and finish vertices of the corresponding route.
Output
For each day output one integer on a separate line  the number of previous routes it intersects with.
Constraints with Subtasks
 Subtask #1[18 points]:
1 ≤ N, Q ≤ 10^{2}  Subtask #2[19 points]:
1 ≤ N, Q ≤ 10^{3}  Subtask #3[21 points]:
1 ≤ N, Q ≤ 5*10^{4}  Subtask #4[42 points]:
1 ≤ N ≤ 2*10^{5}, 1 ≤ Q ≤ 3*10^{5}
Example
Input: 5 1 2 1 3 3 4 3 5 4 4 5 4 2 1 3 1 2 Output: 0 1 2 2
Explanation
Day 1. As there is no previous route, the route from 4 to 5 can't intersect with any round. Hence answer is 0.
Day 2. Route from 4 to 2 intersects with route 1 (at vertices 3 and 4), So the answer is 1.
Day 3. Route from 1 to 3: intersects with both the previous routes. Hence answer is 2.
Day 4. Route from 1 to 2: intersects with route 2 and 3. Hence answer is 2.
Author:  pavel1996 
Tester:  karanaggarwal 
Editorial  http://discuss.codechef.com/problems/TRAVTREE 
Tags  heavydecomp, lca, ltime37, medhard, pavel1996, subtreesum 
Date Added:  14062016 
Time Limit:  1 sec 
Source Limit:  50000 Bytes 
Languages:  C, CPP14, JAVA, PYTH, PYTH 3.6, PYPY, CS2, PAS fpc, PAS gpc, RUBY, PHP, GO, NODEJS, HASK, SCALA, D, PERL, FORT, WSPC, ADA, CAML, ICK, BF, ASM, CLPS, PRLG, ICON, SCM qobi, PIKE, ST, NICE, LUA, BASH, NEM, LISP sbcl, LISP clisp, SCM guile, JS, ERL, TCL, PERL6, TEXT, SCM chicken, CLOJ, FS 
Comments
 Please login at the top to post a comment.
SUCCESSFUL SUBMISSIONS
Fetching successful submissions
HELP
If you are still having problems, see a sample solution here. 