#P6111. [USACO18JAN] MooTube S

[USACO18JAN] MooTube S

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 (1N50001 \leq N \leq 5000), numbered 1N1 \ldots N for convenience. 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. In this way, cows will be recommended videos that are most related to the videos they have already watched.

FJ designed a “relevance” measure, as the name suggests, to determine how related two videos are. He chose N1N - 1 pairs of videos and manually computed the relevance between each pair. Then, FJ built his videos into a tree, where each video is a node, and he manually connected the N1N - 1 pairs of videos. For convenience, FJ chose these N1N - 1 pairs so that any video can reach any other video via a connected path. FJ decides to define the relevance between any two videos as the minimum relevance of any edge along this path.

Farmer John wants to choose a value KK so that, next to any given MooTube video, all other videos with relevance at least KK to that video will be recommended. However, FJ worries that he might recommend too many videos to his cows, which could distract them from producing milk. Therefore, he wants to set an appropriate value of KK. Farmer John would like your help in answering some queries about the recommended videos for different values of KK.

Input Format

The first line contains NN and QQ (1Q50001 \leq Q \leq 5000).

The next N1N - 1 lines describe the pairs 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 with relevance rir_i.

The next QQ lines describe 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 the ii-th query, FJ asks: when K=kiK = k_i, how many videos will appear in the recommended 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