#P4185. [USACO18JAN] MooTube G

[USACO18JAN] MooTube G

Description

In his spare time, Farmer John created a new video sharing service, which he named MooTube. On MooTube, Farmer John’s cows can record, share, and discover many interesting videos. His cows have posted NN videos (1N1051 \leq N \leq 10^5), conveniently numbered 1N1 \ldots N. However, FJ cannot figure out how to help his cows find new videos they might like.

FJ wants to create a “recommended videos” list for each MooTube video. This way, cows will be recommended videos that are most related to the videos they have already watched.

FJ designed a “relevance” metric that, as the name suggests, measures how related two videos are. FJ models his videos as a tree (where each node represents a video) and computes the relevance for all N1N-1 pairs of adjacent videos. In this way, any video can reach any other video via a connected path. FJ defines the relevance of any pair of videos as the minimum relevance along the edges on the path between them.

Farmer John wants to choose a value KK so that, next to any given MooTube video, he will recommend all other videos whose relevance to that video is at least KK. However, FJ worries about recommending too many videos, which might distract the cows from producing milk. Therefore, he wants to set an appropriate value of KK. Farmer John needs your help to answer some questions about the recommended videos for given KK values.

Input Format

The first line contains NN and QQ (1Q1051 \leq Q \leq 10^5).

Each of the next N1N-1 lines describes a pair of videos that FJ compared manually. Each line contains three integers pip_i, qiq_i, and rir_i (1pi,qiN1 \leq p_i, q_i \leq N, 1ri1091 \leq r_i \leq 10^9), indicating that videos pip_i and qiq_i are connected and have relevance rir_i.

Each of the next QQ lines describes one of Farmer John’s QQ queries. Each line contains two integers, kik_i and viv_i (1ki1091 \leq k_i \leq 10^9, 1viN1 \leq v_i \leq N), meaning that in FJ’s ii-th query, when K=kiK = k_i, you should report how many videos would be recommended in the list for video viv_i.

Output Format

Output QQ lines. On the ii-th line, output the answer to FJ’s ii-th query.

4 3
1 2 3
2 3 2
2 4 4
1 2
4 1
3 1
3
0
2

Hint

Translated by ChatGPT 5