Special Path Tree

0

0 votes
Medium
Problem

You are given a weighted tree with N nodes. Now you are given q queries. In each query you are given three integers x,y and z. Now you need to tell what will be the special distance between the two nodes x and y if you root the tree at node z.
Suppose that you want to calculate special distance between two nodes x and y and the tree is rooted at z then you start at node x and you will move towards the node y. Now if you are moving towards the root then add the weights on the edges or else subtract the weight of involved edges if you are moving away from the root.
Note: It is mandatory to view the image to understand the concept of special distance .
So for every query you have to provide the value of this distance.
Input
First line contains a number n as input denoting total number of nodes in the tree
Next n1 lines contain a triplet of integers u,v,w that denote there is an edge between the vertex u and v of the tree and its weight is w.
Next line contains a number q as input.
Next q lines contain a triplet of integers x,y and z.
Output
For every query you need to find the absolute distance between the two nodes x and y if the root is z. Print the answer for each query in the new line.
Constraints
1n105
1u,vn
1q105
1x,y,zn
100w100

Sample Input
5
1 2 1
1 3 4
3 4 2
3 5 3
1
2 5 4
Sample Output
2
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

enter image description here

In the given query the tree needs to be rooted at node numbered 4. Now you have to find the special distance between node 2 and node 5. The path will be 2 - > 1 - > 3 - > 5 . And the special distance will be 1 + 4 - 3 . When you reach at node 3 then to reach 5 you will move away from the root so that weight is subtracted from the total sum

Editor Image

?