PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SRD0000090. Nhãn cạnh còn thiếu (Frank Sinatra)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Nhãn cạnh còn thiếu (Frank Sinatra)

Frank Sinatra

Source: Codeforces Gym

Version: Phuoc Hung OJ Extended

Problem Statement

An undirected tree has nn vertices numbered from 11 to nn. Each edge carries a non-negative integer label. Different edges may have the same label.

For every query consisting of two vertices aa and bb, consider the unique simple path between them. Find the smallest non-negative integer absent from the labels of the edges on this path.

If a=ba=b, the path contains no edges and the answer is 00.

Input

  • The first line contains n,qn,q, the numbers of vertices and queries.
  • Each of the next n−1n-1 lines contains u,v,xu,v,x: an undirected edge joining uu and vv, labelled xx. These edges form a tree.
  • Each of the last qq lines contains query endpoints a,ba,b.

Output

Print exactly qq lines. The jj-th line contains the smallest non-negative integer not found among the edge labels on the path of query jj.

Subtasks

  • Subtask 1 (10 points): n≤30n\le 30, q≤50q\le 50.
  • Subtask 2 (15 points): n≤500n\le 500, q≤500q\le 500.
  • Subtask 3 (25 points): n≤8000n\le 8000, q≤8000q\le 8000.
  • Subtask 4 (50 points): n≤100000n\le 100000, q≤100000q\le 100000.

Complete conditions for all subtasks, subject to the tighter limits above: 2≤n≤1052\le n\le 10^5, 1≤q≤1051\le q\le 10^5, 0≤x≤1090\le x\le 10^9 và 1≤u,v,a,b≤n1\le u,v,a,b\le n.

Examples

Input

7 6
2 1 1
3 1 2
1 4 0
4 5 1
5 6 3
5 7 4
1 3
4 1
2 4
2 5
3 5
3 7

Output

0
1
2
2
3
3

Explanation

The sample edge labels are (1,2):1(1,2):1, (1,3):2(1,3):2, (1,4):0(1,4):0, (4,5):1(4,5):1, (5,6):3(5,6):3, and (5,7):4(5,7):4.

  • Path 1→31\to3 has label set {2}\{2\}, so 0 is missing.
  • Path 4→14\to1 has label set {0}\{0\}, so 1 is missing.
  • Path 2→1→42\to1\to4 has labels 1,01,0, so 2 is missing.
  • Path 2→1→4→52\to1\to4\to5 has labels 1,0,11,0,1, again giving 2.
  • Path 3→1→4→53\to1\to4\to5 has labels 2,0,12,0,1, giving 3.
  • Path 3→1→4→5→73\to1\to4\to5\to7 has labels 2,0,1,42,0,1,4, also giving 3.