File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } n
3
+ * @param {number[][] } restrictions
4
+ * @param {number[][] } requests
5
+ * @return {boolean[] }
6
+ */
7
+ var friendRequests = function ( n , restrictions , requests ) {
8
+ /*
9
+ 对于 [a, b] 一个 request 来说,如果 (x, y) 存在于 restrictions 里面
10
+ 就说明不能够合在一起,x 是 a 代表的集合中的任意元素,y 是 b 代表的集合中的任意元素
11
+ 因此 restrictions 也是需要去动态更新的,并查集更新的时候要更新成根节点的限制关系
12
+
13
+ 0 x 1
14
+ 1 - 2
15
+ 0 x 2
16
+ */
17
+ const r = [ ...Array ( n ) ] . map ( ( ) => [ ] )
18
+ for ( const [ x , y ] of restrictions ) {
19
+ r [ x ] [ y ] = r [ y ] [ x ] = 1
20
+ }
21
+ const fa = [ ...Array ( n ) ] . map ( ( _ , idx ) => idx )
22
+ const get = ( x ) => {
23
+ if ( fa [ x ] === x ) return x
24
+ return fa [ x ] = get ( fa [ x ] )
25
+ }
26
+ function merge ( x , y ) {
27
+ const fx = get ( x ) ; const fy = get ( y )
28
+ fa [ fx ] = fy
29
+ }
30
+ const m = requests . length
31
+ const ans = Array ( m ) . fill ( false )
32
+ for ( let i = 0 ; i < m ; i ++ ) {
33
+ const [ a , b ] = requests [ i ]
34
+ if ( r [ get ( a ) ] [ get ( b ) ] ) ans [ i ] = false
35
+ else {
36
+ ans [ i ] = true
37
+
38
+ for ( let j = 0 ; j < n ; j ++ ) {
39
+ if ( r [ get ( j ) ] [ get ( a ) ] ) r [ get ( j ) ] [ get ( b ) ] = r [ get ( b ) ] [ get ( j ) ] = true
40
+ if ( r [ get ( j ) ] [ get ( b ) ] ) r [ get ( j ) ] [ get ( a ) ] = r [ get ( a ) ] [ get ( j ) ] = true
41
+ }
42
+
43
+ merge ( a , b )
44
+ }
45
+ }
46
+ return ans
47
+ } ;
You can’t perform that action at this time.
0 commit comments