Under construction

Still being built. Things may change

Intellectual Prefix Maxima

Time limit4sMemory limit512 MB

Summary
For each query on a weighted tree, compute the sum of prefix maxima of the edge weights along the path from u to v.
Level

Hard9 of 10

Topics
Tree, Divide and conquer, Binary search
Solved
No attempts yet

Problem

A tree is an undirected graph in which any two vertices are connected by exactly one path. You are given a weighted tree with nn vertices, where w(i,j)w(i, j) is the weight of the edge between vertices ii and jj. Consider a simple path P=(u,s1,…,st−1,v)P = (u, s_1, \dots, s_{t-1}, v) from vertex uu to vertex vv. Denote the sequence of edge weights on path PP by a=(a1,a2,…,at)a = (a_1, a_2, \dots, a_t), where a1=w(u,s1)a_1 = w(u, s_1), a2=w(s1,s2)a_2 = w(s_1, s_2), …\dots, at=w(st−1,v)a_t = w(s_{t-1}, v).

Let f(u,v)=∑i=1tmax⁡j=1…i{aj}f(u, v) = \sum_{i=1}^{t} \max_{j=1 \dots i}\{a_j\} be the sum of prefix maxima of aa. You are given qq queries, each described by two integers uu and vv. For each query, compute f(u,v)f(u, v).

Input

The first line contains two integers nn and qq (1≤n≤2⋅1051 \le n \le 2 \cdot 10^5, 1≤q≤1061 \le q \le 10^6), separated by a single space: the number of vertices in the tree and the number of queries.

Each of the next n−1n - 1 lines contains three integers aia_i, bib_i, and cic_i (1≤ai,bi≤n1 \le a_i, b_i \le n, ai≠bia_i \ne b_i, 1≤ci≤1091 \le c_i \le 10^9): the vertices connected by the ii-th edge and its weight. It is guaranteed that the given edges form a tree.

Each of the next qq lines contains two integers uiu_i and viv_i (1≤ui,vi≤n1 \le u_i, v_i \le n): the ii-th query.

Output

Print qq lines. The ii-th line contains a single integer: the answer to the ii-th query.

Examples1

  1. Example 1

    Input
    5 4
    1 2 2
    2 3 1
    3 4 3
    3 5 4
    1 4
    1 5
    4 2
    5 2
    
    Expected output
    7
    8
    6
    8