Píngjūn shù wèntí

Time limit: 6s Memory limit: 1024MB Input: Output:

Task

You are given a tree with NN nodes, labeled from 11 to NN, where each edge has an integer weight. We define the distance between nodes aa and bb as the sum of weights on the unique simple path that connects them.

You are also given QQ queries of the form K L RK\ L\ R, where you have to determine the shortest distance between node KK and any node between LL and RR, inclusive.

Input data

The first line of stdin contains two space-separated integers, NN and QQ.

Each of the next N−1N-1 lines of stdin contains three space-separated integers, aa, bb and cc, representing a weighted edge connecting nodes aa and bb with weight cc.

Each of the next QQ lines of stdin contains three space-separated integers, KK, LL and RR, representing a query, as described above.

Output data

Each of the next QQ lines of stdout will contain an integer DD, representing the shortest distance to any node between LL and RR, inclusive.

Constraints and clarifications

  • 1≤N,Q≤300 0001 \leq N, Q \leq 300 \ 000;
  • 1≤ai,bi≤N1 \leq a_i, b_i \leq N;
  • 1≤ci≤10 0001 \leq c_i \leq 10 \ 000;
# Score Constraints
1 15 1≤N,Q≤1 0001 \leq N, Q \leq 1 \ 000
2 12 1≤N,Q≤30 0001 \leq N, Q \leq 30 \ 000
3 13 1≤N,Q≤100 0001 \leq N, Q \leq 100 \ 000
4 20 1≤N,Q≤100 0001 \leq N, Q \leq 100 \ 000, the tree is a path
5 15 1≤N,Q≤200 0001 \leq N, Q \leq 200 \ 000
6 25 No further restrictions.

Example 1

stdin

5 3
1 2 10
2 3 10
3 4 10
4 5 10
1 3 5
3 1 2
2 4 5

stdout

20
10
20

Explanation

In the first sample case, the solutions are nodes 33, 22 and 44 for each of the queries.

Example 2

stdin

6 3
1 2 5
1 3 10
1 4 2
1 5 8
1 6 3
2 4 6
4 2 3
3 5 6

stdout

7
7
13

Explanation

In the second sample case, the solutions are nodes 44, 22 and 66 for each of the queries.

Example 3

stdin

3 1
1 2 5
1 3 5
1 2 3

stdout

5

Explanation

In the third sample case, the solution is node 22.

Log in or sign up to be able to send submissions!