Isn't your problem very similar to Timus Online Judge 1471.Tree ? The only difference is that the nodes are weighed in your task, and the edges are weighed in Ural 1471.Tree.
This is a typical LCA problem.
Make one of the nodes as the root of the tree (if necessary), and then calculate the distance dist [i] of all other nodes to the root, which takes O (N) time using BFS / DFS. Then for each query (A, B) find LCA L of (A, B), then the distance between (A, B) is dist [A] + dist [B] - 2 * dist [L].
However, in your problem, you may need to convert the weight of the node to the weight of the edge.
If you are not familiar with the LCA algorithm, here is a very good site that can help you.
source share