AlgoUniversity
  • Go Back
Discussion
Tree Of Co Primes :

Author

Shikhar Mehrotra

Difficulty Level : Medium

Submissions : 145

Asked In : Uber

Marks :20

: 5 | : 0

There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of $$$N$$$ nodes numbered from $$$0$$$ to $$$N-1$$$ and exactly $$$N-1$$$ edges . Each node has a value associated with it i.e $$$nums[i]$$$ denote the value on node $$$i$$$, and the root of the tree is node $$$0$$$.

Two values $$$x$$$ and $$$y$$$ are coprime if $$$gcd(x, y)==1$$$ where $$$gcd(x, y)$$$ is the greatest common divisor of $$$x$$$ and $$$y$$$.

An ancestor of a node $$$i$$$ is any other node on the shortest path from node $$$i$$$ to the root. A node is not considered an ancestor of itself.

Output $$$N$$$ space-separated integers, where $$$i_{th}$$$ integer (0-based indexing) represents the closest ancestor to node $$$i$$$ such that $$$nums[i]$$$ and $$$nums[i_{th}]$$$ are coprime, or $$$-1$$$ if there is no such ancestor.

Input

The first line contains a single integer $$$1\le N \le 10^{5}$$$.

The second line contains $$$N$$$ space separated integers where $$$0\le i < n$$$ integer denotes $$$1\le nums[i]\le 50$$$.

Following $$$N-1$$$ lines contains two space separated integers $$$u$$$ and $$$v$$$ which denotes $$$u$$$ and $$$v$$$ are connected by an edge.

Output

Output $$$N$$$ space-separated integers, where $$$i_{th}$$$ integer (0-based indexing) represents the closest ancestor to node $$$i$$$ such that $$$nums[i]$$$ and $$$nums[i_{th}]$$$ are coprime, or $$$-1$$$ if there is no such ancestor.

Examples

Input
4
2 3 3 2
0 1
1 2
1 3
Output
-1 0 0 1 
Input
7
5 6 10 2 3 6 15
0 1
0 2
1 3
1 4
2 5
2 6
Output
-1 0 -1 0 0 0 -1 

You need to login to view your submissions.

You need to login to view all submissions.

Loading...

Result : Executed

Loading...

Feel something is wrong with the test cases?

Result : Accepted

Test Cases :

You need to Log In
We're glad that you want to attempt this problem!

But to Run or Submit the Problem, you need to Log In.

Continue to Log In
Challenge Submitted!

Your challenge has been submitted successfully.

You will get a response soon via WhatsApp or Email.

Challenge
Facing issue while trying to solve the problem! Don't worry, we got you covered!

Do let us know your issue.

Looks good!
Please enter your issue / feedback.

How do we get in touch with you?
Looks good!
Please enter your phone no.
Looks good!
Please enter your email address.