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

#GL0000357. Caisa và cây (Caisa and Tree)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Caisa và cây (Caisa and Tree)

Caisa and Tree

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

A tree on nn vertices is rooted at vertex 11, with a positive value ava_v at each vertex. Process qq operations in order:

  • 1 v: report the closest proper ancestor uu of vv such that gcd⁡(au,av)>1\gcd(a_u,a_v)>1. Output -1 if none exists.
  • 2 v w: replace the value at vertex vv with ww for future queries.

The ancestor must be distinct from vv; choosing the closest ancestor means maximizing its depth.

Input

  • First line: n,qn,q.
  • Second line: vertex values a1,…,ana_1,\ldots,a_n.
  • Next n−1n-1 lines: edges u,vu,v of the tree.
  • Next qq lines: operations 1 v or 2 v w.

Output

For each type-1 operation, print the vertex index or -1, on its own line. Type-2 operations print nothing.

Global conditions: 1≤u,v≤n1\le u,v\le n, 1≤ai,w≤2⋅1061\le a_i,w\le2\cdot10^6, and at most 50 updates occur.

Subtasks

  • Subtask 1 (20 points): $1 <= n,q <= 30; 1 <= a_i,w <= 100; update queries <= 10$.
  • Subtask 2 (30 points): $1 <= n,q <= 3000; 1 <= a_i,w <= 10^5; update queries <= 30$.
  • Subtask 3 (50 points): $1 <= n,q <= 10^5; 1 <= a_i,w <= 2*10^6; update queries <= 50$.

All queried vertices satisfy 1≤v≤n1\le v\le n, each edge joins distinct vertices, and there are exactly qq operations.

Examples

Example 1

Input

4 6
10 8 4 3
1 2
2 3
3 4
1 1
1 2
1 3
1 4
2 1 9
1 4

Output

-1
1
2
-1
1

Explanation

Vertex 2 matches ancestor 1 by gcd(8,10)=2; vertex 3 matches nearest ancestor 2 by gcd(4,8)=4. Vertex 4 (value 3) initially matches no ancestor; after vertex 1 becomes 9, the answer for vertex 4 is 1.

Example 2

Input

1 3
6
1 1
2 1 15
1 1

Output

-1
-1

Explanation

A one-vertex tree has no proper ancestor, even after the root value changes.