4
4
* @param {number[][] } queries
5
5
* @return {boolean[] }
6
6
*/
7
- const distanceLimitedPathsExist = function ( n , edgeList , queries ) {
8
- edgeList . sort ( ( a , b ) => a [ 2 ] - b [ 2 ] )
9
- let q = queries . length ;
10
- const ans = Array ( q ) . fill ( false ) ;
11
- const order = Array ( q ) . fill ( 0 ) ;
12
- for ( let i = 0 ; i < q ; ++ i ) order [ i ] = i ;
13
- order . sort ( ( i , j ) => queries [ i ] [ 2 ] - queries [ j ] [ 2 ] )
14
- const uf = new UnionFind ( n ) ;
15
- let idx = 0 ;
16
- for ( let i of order ) {
17
- let limit = queries [ i ] [ 2 ] ;
18
- while ( idx < edgeList . length && edgeList [ idx ] [ 2 ] < limit ) {
19
- let u = edgeList [ idx ] [ 0 ] , v = edgeList [ idx ] [ 1 ] ;
20
- uf . union ( u , v ) ;
21
- idx ++ ;
22
- }
23
- let u0 = queries [ i ] [ 0 ] , v0 = queries [ i ] [ 1 ] ;
24
- if ( uf . find ( u0 ) === uf . find ( v0 ) ) ans [ i ] = true ;
7
+ const distanceLimitedPathsExist = function ( n , edgeList , queries ) {
8
+ edgeList . sort ( ( a , b ) => a [ 2 ] - b [ 2 ] )
9
+ const m = queries . length
10
+ const ans = Array ( m ) . fill ( false )
11
+ const order = Array ( m ) . fill ( 0 )
12
+ for ( let i = 0 ; i < m ; ++ i ) order [ i ] = i
13
+ order . sort ( ( i , j ) => queries [ i ] [ 2 ] - queries [ j ] [ 2 ] )
14
+ const uf = new UnionFind ( n )
15
+ let idx = 0
16
+ for ( let i of order ) {
17
+ const limit = queries [ i ] [ 2 ]
18
+ while ( idx < edgeList . length && edgeList [ idx ] [ 2 ] < limit ) {
19
+ const u = edgeList [ idx ] [ 0 ] ,
20
+ v = edgeList [ idx ] [ 1 ]
21
+ uf . union ( u , v )
22
+ idx ++
25
23
}
26
- return ans ;
27
- } ;
24
+ const u0 = queries [ i ] [ 0 ] ,
25
+ v0 = queries [ i ] [ 1 ]
26
+ if ( uf . find ( u0 ) === uf . find ( v0 ) ) ans [ i ] = true
27
+ }
28
+ return ans
29
+ }
28
30
class UnionFind {
29
31
constructor ( n ) {
30
32
this . parents = Array ( n )
@@ -33,7 +35,7 @@ class UnionFind {
33
35
this . ranks = Array ( n ) . fill ( 0 )
34
36
}
35
37
root ( x ) {
36
- while ( x !== this . parents [ x ] ) {
38
+ while ( x !== this . parents [ x ] ) {
37
39
this . parents [ x ] = this . parents [ this . parents [ x ] ]
38
40
x = this . parents [ x ]
39
41
}
0 commit comments