-
Notifications
You must be signed in to change notification settings - Fork 2
/
1766.互质树.js
70 lines (60 loc) · 1.17 KB
/
1766.互质树.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* @lc app=leetcode.cn id=1766 lang=javascript
*
* [1766] 互质树
*/
// @lc code=start
/**
* @param {number[]} nums
* @param {number[][]} edges
* @return {number[]}
*/
var getCoprimes = function(nums, edges) {
const node = {}
const ans = Array(nums.length).fill(null)
function addNode(f, t){
if(!node[f]){
node[f]=[]
}
node[f].push(t)
}
edges.forEach(([f, t])=>{
addNode(f, t)
addNode(t, f)
})
function gcd(a, b){
while(b) [a, b] = [b, a % b];
return a;
}
const map = []
for(let i=0; i<51; i++){
map[i]=[]
for(let j=0; j<51; j++){
map[i][j]= gcd(i,j)
}
}
let pi=-1
let path=Array(nums.length)
function check(v){
if(ans[v]!==null) return
ans[v] = -1
let a = nums[v]
for(let k=pi; k>=0; k--){
let b = nums[path[k]]
if(map[a][b]===1){
ans[v]=path[k]
break
}
}
if(node[v]) {
path[++pi]=v
node[v].forEach(child=>check(child))
pi--
}
}
for(let i=0; i<nums.length; i++){
check(i)
}
return ans
};
// @lc code=end