Pasture Walking
InterviewTime limit1sMemory limit128 MB
Given a weighted tree with N vertices and Q queries, find the path length between each queried pair of vertices.
- Level
Medium5 of 10
- Topics
- Tree, DFS, Prefix sum, Graph
- Solved
- No attempts yet
Problem
There are cows (), conveniently numbered , grazing among pastures that are also numbered . Most conveniently of all, cow is grazing in pasture .
Some pairs of pastures are connected by bidirectional walkways that the cows can traverse, and there are walkways in total. Walkway connects pastures and (, ) and has length ().
The walkways are arranged so that between any two distinct pastures there is exactly one path of walkways. In other words, the walkways form a tree.
The cows are very social and want to visit one another often. For pairs of pastures (), each given as a query (, , ), compute the length of the path connecting them.
Input
- Line 1: Two space-separated integers and .
- Lines 2 to : Line contains three space-separated integers , , and .
- Lines to : Each line contains two space-separated integers and , the two distinct pastures the cows wish to travel between.
Output
- For each query , print on line the length of the path between the two pastures given in that query. ( lines in total.)
Hint
- First query: the walkway between pastures and has length .
- Second query: travel along the walkway between pastures and , then the one between and , and finally the one between and , for a total length of .