1
var areConnected = function (n, threshold, queries) {2
// if(gcd(a,b)>threshold), a and b are connected4
// 2 is connected with : 2, 4,6,8,10,12,14,16, (gcd(2,y)=2)5
// 3 is connected with : 3,6,9,12,... (gcd(3,y)=3)6
// 4 is connected with : 4,8,12,16,20,24,28, (gcd(4,y)=4)7
// 6 is connected with : 6,12,18...,cos (gcd(6,y)=6)8
// 5 is connected with : 10,15,20,25,...n cos (gcd(5,y)=6)11
let dsu = new UnionFind(n + 1); //to map n=>n (no node 0 on my question)14
let node = threshold + 1;16
node++ //basically this ensures that the road exists18
//cos gcd(node,secondnode)==node >threshold19
for (let secondnode = node + node; secondnode <= n; secondnode += node)20
dsu.union(node, secondnode);22
return queries.map(([a, b]) => dsu.sameGroup(a, b));26
//the total count of different elements(not groups) in this union find28
//tracks the sizes of each of the components(groups/sets)29
//groupsize[a] returns how many elements the component with root a has30
this.groupSize = [...Array(size)];31
//number of components(groups) in the union find32
this.numComponents = size;33
//points to the parent of i, if parent[i]=i, i is a root node34
this.parent = [...Array(size)]; //which is also the index of the group36
//put every element into its own group38
for (let i = 0; i < size; i++) {39
this.groupSize[i] = i;44
//returns to which component (group) my element belongs to45
// (n) --Amortized constant time46
// Update: Also compresses the paths so that each child points to its50
//find the parent of the group the elemnt belongs to51
// When root===parent[root] is always the parent of that group (root)52
while (root != this.parent[root]) root = this.parent[root];54
// Compression, point the element to its parent if its not already pointed55
// Tldr: Not only do I point my element to its actual root, i point any56
// inbetween elements to that root aswell57
while (element != root) {58
let next = this.parent[element];59
this.parent[element] = root;66
//Unifies the sets containing A and B67
// if not already unified68
// (n) --Amortized constant time70
let root1 = this.find(A), //parent of A71
root2 = this.find(B); //parent of B75
// I want to put the set with fewer elements76
// to the one with more elemenets77
if (this.groupSize[root1] < this.groupSize[root2]) {78
this.groupSize[root2] += this.groupSize[root1];79
this.parent[root1] = this.parent[root2];81
this.groupSize[root1] += this.groupSize[root2];82
this.parent[root2] = this.parent[root1];85
this.numComponents--; //cos 1 less group, since i merged 288
//same parent=>samegroup89
sameGroup = (A, B) => this.find(A) == this.find(B);91
//essentially the groupSize of its parent's group92
sizeOfGroup = (A) => this.groupSize[this.find(A)];