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

#GL0000396. Đếm cặp chỉ số nguyên tố cùng nhau trong cây con (Counting Coprime Vertex Indices in a Tree)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Đếm cặp chỉ số nguyên tố cùng nhau trong cây con (Counting Coprime Vertex Indices in a Tree)

Counting Coprime Vertex Indices in a Tree

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a rooted tree with vertex indices 1,2,…,n1,2,\ldots,n and root 11. You must process qq independent subtree queries.

For a query vertex xx, denote the vertex set of its rooted subtree by T(x)T(x). Count all pairs satisfying

u,v∈T(x),v<u,gcd⁡(u,v)=1.u,v\in T(x),\qquad v<u,\qquad\gcd(u,v)=1.

The strict inequality v<uv<u ensures each unordered pair is counted exactly once. The GCD is applied to the vertex indices u,vu,v; there is no array of vertex weights in this problem.

Input

  • First line: integers n,qn,q.
  • Next line: n−1n-1 integers p2,…,pnp_2,\ldots,p_n, where pip_i is the parent of vertex ii (the list is empty when n=1n=1).
  • Next qq lines: one query vertex xx per line.

The parents describe a valid tree rooted at 11. A parent index need not be smaller than its child's index.

Output

For each query, print one 64-bit integer: the number of valid pairs in the queried subtree.

Subtasks

  • Subtask 1 (20 points): 1≤n,q≤1001\le n,q\le100; 1≤pi,x≤n1\le p_i,x\le n; valid rooted tree.

  • Subtask 2 (30 points): 1≤n,q≤5 0001\le n,q\le5\,000; 1≤pi,x≤n1\le p_i,x\le n; valid rooted tree.

  • Subtask 3 (50 points): 1≤n,q≤100 0001\le n,q\le100\,000; 1≤pi,x≤n1\le p_i,x\le n; valid rooted tree.

Examples

Example 1 (official)

Input

2 2
1
1
2

Output

1
0

Explanation

The subtree of vertex 11 contains indices 1,21,2; the only pair is coprime. The subtree of vertex 22 contains one vertex and therefore contributes no pairs.

Example 2 (additional)

Input

4 4
4 2 1
1
4
2
3

Output

5
2
1
0

Explanation

The tree is the chain 1→4→2→31\to4\to2\to3. Among all six pairs at the root, only (2,4)(2,4) is not coprime, so the first answer is 55. The subtree of vertex 44 contains {4,2,3}\{4,2,3\} and has two coprime pairs; vertex 22 has one coprime pair, (2,3)(2,3); the leaf vertex 33 has none.