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

#SRD0000106. Đồ thị đa sắc của Kitayuta (Mr. Kitayuta's Colorful Graph)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Đồ thị đa sắc của Kitayuta (Mr. Kitayuta's Colorful Graph)

Mr. Kitayuta's Colorful Graph

Source: Codeforces Version: Phuoc Hung OJ Extended

Problem Statement

Mr. Kitayuta owns an undirected multigraph with nn vertices numbered 11 through nn and mm edges. Each edge joins two different vertices ai,bia_i,b_i and has an integer color cic_i.

There may be multiple edges between the same two vertices if their colors differ. However, no two edges have the same triple (ai,bi,ci)(a_i,b_i,c_i) with endpoints written in the order ai<bia_i<b_i.

For each query consisting of two distinct vertices u,vu,v, count the colors cc such that uu and vv are connected by a path consisting only of edges of color cc. Edges of different colors cannot be mixed when evaluating a single color.

A pair may be connected by several different colors; each valid color contributes one to the answer.

Input

  • Line 1: n m.
  • The next mm lines: a_i b_i c_i describing an undirected edge of color cic_i.
  • The next line: number of queries q.
  • The final qq lines: u v, where uevu e v.

Output

For each query, output the number of qualifying colors on a separate line.

Subtasks

  • Subtask 1 (10 points): 2≤n≤302\le n\le 30, 1≤m≤801\le m\le 80, 1≤q≤1001\le q\le 100; 1≤ai<bi≤n1\le a_i<b_i\le n, 1≤ci≤m1\le c_i\le m; distinct triples (ai,bi,ci)(a_i,b_i,c_i); 1≤u,v≤n1\le u,v\le n, u≠vu\ne v.
  • Subtask 2 (20 points): 2≤n≤2002\le n\le 200, 1≤m≤7001\le m\le 700, 1≤q≤20001\le q\le 2000; 1≤ai<bi≤n1\le a_i<b_i\le n, 1≤ci≤m1\le c_i\le m; distinct triples (ai,bi,ci)(a_i,b_i,c_i); 1≤u,v≤n1\le u,v\le n, u≠vu\ne v.
  • Subtask 3 (30 points): 2≤n≤50002\le n\le 5000, 1≤m≤150001\le m\le 15000, 1≤q≤200001\le q\le 20000; 1≤ai<bi≤n1\le a_i<b_i\le n, 1≤ci≤m1\le c_i\le m; distinct triples (ai,bi,ci)(a_i,b_i,c_i); 1≤u,v≤n1\le u,v\le n, u≠vu\ne v.
  • Subtask 4 (40 points): 2≤n≤1000002\le n\le 100000, 1≤m≤1000001\le m\le 100000, 1≤q≤1000001\le q\le 100000; 1≤ai<bi≤n1\le a_i<b_i\le n, 1≤ci≤m1\le c_i\le m; distinct triples (ai,bi,ci)(a_i,b_i,c_i); 1≤u,v≤n1\le u,v\le n, u≠vu\ne v.

Examples

Example 1

Input

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

Output

2
1
0

Explanation

For (1,2)(1,2), both colors 11 and 22 provide a path, so the answer is 22. For (3,4)(3,4), color 33 connects the vertices along 3→2→43\to2\to4, so the answer is 11. There is no monochromatic path from 11 to 44, giving 00.

Example 2

Input

5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4

Output

1
1
1
1
2

Explanation

The four color-11 edges form a star centered at vertex 55, connecting all five vertices in color 11. Color-22 edges form the path 1−2−3−41-2-3-4. Thus, (1,4)(1,4) is connected in two colors, while any queried pair involving vertex 55 is connected only in color 11.