This page is still under construction.

Parts of this page are still being built. What you see may change.

Pasture Walking

Interview

Time limit1sMemory limit128 MB

Summary
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 NN cows (2≤N≤1,0002 \le N \le 1{,}000), conveniently numbered 1..N1..N, grazing among NN pastures that are also numbered 1..N1..N. Most conveniently of all, cow ii is grazing in pasture ii.

Some pairs of pastures are connected by bidirectional walkways that the cows can traverse, and there are N−1N-1 walkways in total. Walkway ii connects pastures AiA_i and BiB_i (1≤Ai≤N1 \le A_i \le N, 1≤Bi≤N1 \le B_i \le N) and has length LiL_i (1≤Li≤10,0001 \le L_i \le 10{,}000).

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 QQ pairs of pastures (1≤Q≤1,0001 \le Q \le 1{,}000), each given as a query p1,p2p_1, p_2 (1≤p1≤N1 \le p_1 \le N, 1≤p2≤N1 \le p_2 \le N, p1≠p2p_1 \ne p_2), compute the length of the path connecting them.

Input

  • Line 1: Two space-separated integers NN and QQ.
  • Lines 2 to NN: Line i+1i+1 contains three space-separated integers AiA_i, BiB_i, and LiL_i.
  • Lines N+1N+1 to N+QN+Q: Each line contains two space-separated integers p1p_1 and p2p_2, the two distinct pastures the cows wish to travel between.

Output

  • For each query ii, print on line ii the length of the path between the two pastures given in that query. (QQ lines in total.)

Hint

  • First query: the walkway between pastures 11 and 22 has length 22.
  • Second query: travel along the walkway between pastures 33 and 44, then the one between 44 and 11, and finally the one between 11 and 22, for a total length of 77.

Examples3

  1. Example 1

    Input
    4 2
    2 1 2
    4 3 2
    1 4 3
    1 2
    3 2
    
    Expected output
    2
    7
    
  2. Example 2

    Input
    5 3
    1 2 1
    2 3 2
    3 4 3
    4 5 4
    1 5
    2 4
    5 3
    
    Expected output
    10
    5
    7
    
  3. Example 3

    Input
    5 3
    1 2 10
    1 3 20
    1 4 30
    1 5 40
    2 3
    4 5
    2 5
    
    Expected output
    30
    70
    50