Requiem for a Dream
Practice
4.5 (17 votes)
Data structures
Tree
Approved
Medium Hard
Segment tree
Problem
82% Success 226 Attempts 50 Points 2s Time Limit 256MB Memory 1024 KB Max Code

The link to the Russian translation.

Enzo is trying to reach Bonnie in her dream. Bonnie's dreamland is so big. It has n cities and n-1 roads. One can go from any city to any other city using only these roads. So, it means there's a unique shortest path between any two cities. Each road has an integer length.

For a sequence of integers a1, a2, ..., ak, sum(l, r) = al + al+1 + ... + ar-1 (1 ≤ l ≤ r ≤ k+1, so by definition sum(x, x) = 0).

prettiness(al + al+1 + ... + ar-1) = max(sum(l, r)) for 1 ≤ l ≤ r ≤ k+1.

Enzo is too mysterious and curious, he has q questions (for what, we don't know). You're his only programmer friend, so he asks you the questions. In each question he gives you v and u and you should tell him the value of goodness(v, u) which can be calculated as follows: suppose e1, e2, ..., ek are the roads on the shortest path from v to u , in order we see them when we go from v to u (if v = u, then k = 0). goodness(v, u) = prettiness(length(e1), length(e2), ..., length(ek)).

Input

The first line of input contains two integers n and q (1 ≤ n, q ≤ 105).

The next n-1 lines contain the roads. Each line contains 3 integers v, u, w meaning there is a road between v and u with length equal to w (1 ≤ v, u ≤ n, v ≠ u, |w| ≤ 109).

The next q lines contain the questions. Each contains two integers v and u (1 ≤ v, u ≤ n).

Output

Print the answer to each question in one line.

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
8 votes
Tags:
AlgorithmsApprovedBinary SearchMediumOpenSorting
Points:50
10 votes
Tags:
ApprovedMedium-Hard
Points:50
22 votes
Tags:
Medium-Hard