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

#GL0000395. Đếm cặp nguyên tố cùng nhau trong cây con (Coprime Pairs in Rooted Subtrees)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Đếm cặp nguyên tố cùng nhau trong cây con (Coprime Pairs in Rooted Subtrees)

Coprime Pairs in Rooted Subtrees

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given an undirected tree with nn vertices, rooted at vertex 11. Each vertex ii holds a positive integer value aia_i.

For every vertex xx, count the number of unordered pairs of distinct vertices {u,v}\{u,v\} such that both vertices belong to the subtree rooted at xx and

gcd⁡(au,av)=1.\gcd(a_u,a_v)=1.

The subtree includes xx itself and all descendants of xx. In this problem, the values au,ava_u,a_v are used in the GCD, not the vertex indices. Each unordered pair is counted once.

Input

  • The first line contains nn.
  • The second line contains nn integers a1,…,ana_1,\ldots,a_n.
  • Each of the next n−1n-1 lines contains two vertices u,vu,v connected by an edge.

Edges can be listed in any order. They form a valid tree.

Output

Print nn lines. Line xx must contain the number of qualifying pairs in the subtree of xx. Use 64-bit integers for the answers.

Subtasks

  • Subtask 1 (20 points): 1≤n≤1001\le n\le100; 1≤ai≤1001\le a_i\le100; 1≤u,v≤n1\le u,v\le n, u≠vu\ne v; valid tree.

  • Subtask 2 (30 points): 1≤n≤5 0001\le n\le5\,000; 1≤ai≤10 0001\le a_i\le10\,000; 1≤u,v≤n1\le u,v\le n, u≠vu\ne v; valid tree.

  • Subtask 3 (50 points): 1≤n≤100 0001\le n\le100\,000; 1≤ai≤100 0001\le a_i\le100\,000; 1≤u,v≤n1\le u,v\le n, u≠vu\ne v; valid tree.

Examples

Example 1 (official)

Input

8
6 1 10 1 15 7 6 14
1 2
1 3
2 4
2 5
3 6
6 7
6 8

Output

18
3
2
0
0
1
0
0

Explanation

The subtree of vertex 22 contains values 1,1,151,1,15; all three unordered pairs have GCD 11. The subtree of vertex 66 has values 7,6,147,6,14 and only (7,6)(7,6) qualifies. Vertex 33 contributes two valid pairs in its own subtree, while the root contains 1818 valid pairs in total.

Example 2 (official)

Input

3
6 10 15
1 2
2 3

Output

0
0
0

Explanation

Each pair among 6,10,156,10,15 has GCD greater than 11, even though the GCD of all three values is 11.