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

#GL0000367. Tích GCD trên đường đi của cây (Prince's Problem — Product of GCD on a Tree Path)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tích GCD trên đường đi của cây (Prince's Problem — Product of GCD on a Tree Path)

Prince's Problem — Product of GCD on a Tree Path

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given an undirected tree of nn vertices. Vertex ww has a fixed positive integer label awa_w.

For each query (u,v,x)(u,v,x), consider the unique simple path from uu to vv, including both endpoints. Let P(u,v)P(u,v) be its vertices. Compute

$$F(u,v,x)=\prod_{w\in P(u,v)}\gcd(x,a_w)\pmod{10^9+7}.$$

If u=vu=v, the product has exactly one factor, gcd⁡(x,au)\gcd(x,a_u). No labels are updated.

Input

  • Line 1: integer nn.
  • Next n−1n-1 lines: edges ui,viu_i,v_i.
  • Next line: nn labels a1,…,ana_1,\ldots,a_n.
  • Next line: integer qq.
  • Next qq lines: queries u,v,xu,v,x.

Output

Print one answer F(u,v,x)F(u,v,x) per line, in query order.

Subtasks

  • Subtask 1 (20 points): 1≤n≤251\le n\le25; 1≤q≤251\le q\le25; 1≤ai,x≤1501\le a_i,x\le150.
  • Subtask 2 (30 points): 1≤n≤20001\le n\le2000; 1≤q≤20001\le q\le2000; 1≤ai,x≤100001\le a_i,x\le10000.
  • Subtask 3 (50 points): 1≤n,q≤1000001\le n,q\le100000; 1≤ai,x≤1071\le a_i,x\le10^7.

Every input describes a tree; all vertex indices lie in [1,n][1,n] and edge endpoints differ.

Examples

Example 1

Input

4
1 2
1 3
1 4
6 4 9 5
3
2 3 6
2 3 2
3 4 7

Output

36
4
1

Explanation

For (2,3,6)(2,3,6) the path is 2→1→32\to1\to3 and the labels are 4,6,94,6,9, giving $\gcd(6,4)\cdot\gcd(6,6)\cdot\gcd(6,9)=2\cdot6\cdot3=36$. With x=2x=2, the same path yields 2⋅2⋅1=42\cdot2\cdot1=4. For (3,4,7)(3,4,7), all three labels on the path are coprime to 77, giving 11.

Example 2

Input

1
12
3
1 1 18
1 1 5
1 1 12

Output

6
1
12

Explanation

The only path consists of a single vertex with label 1212. The answers are respectively gcd⁡(12,18)=6\gcd(12,18)=6, gcd⁡(12,5)=1\gcd(12,5)=1, and gcd⁡(12,12)=12\gcd(12,12)=12.