File tree 1 file changed +65
-0
lines changed
1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } nums
3
+ * @param {number[][] } edges
4
+ * @return {number }
5
+ */
6
+ var componentValue = function ( nums , edges ) {
7
+ const n = nums . length ;
8
+ if ( n === 1 ) return 0 ;
9
+ const total = nums . reduce ( ( a , b ) => a + b , 0 ) ;
10
+ const g = Array . from ( { length : n } , ( ) => [ ] ) ;
11
+ const indegree = Array ( n ) . fill ( 0 ) ;
12
+ for ( const [ u , v ] of edges ) {
13
+ g [ u ] . push ( v ) ;
14
+ g [ v ] . push ( u ) ;
15
+ indegree [ u ] ++ ;
16
+ indegree [ v ] ++ ;
17
+ }
18
+ const sums = [ ]
19
+ for ( let s = 1 ; s * s <= total ; s ++ ) {
20
+ if ( total % s === 0 ) {
21
+ sums . push ( s ) ;
22
+ sums . push ( total / s ) ;
23
+ }
24
+ }
25
+ sums . sort ( ( a , b ) => a - b ) ;
26
+ let res = 0
27
+ for ( const s of sums ) {
28
+ const ind = [ ...indegree ] ;
29
+ const q = [ ] ;
30
+ const visited = Array ( n ) . fill ( false ) ;
31
+ const sum = [ ...nums ] ;
32
+ for ( let i = 0 ; i < n ; i ++ ) {
33
+ if ( ind [ i ] === 1 ) {
34
+ q . push ( i ) ;
35
+ visited [ i ] = true ;
36
+ }
37
+ }
38
+ let flag = true ;
39
+ while ( q . length ) {
40
+ const cur = q . shift ( ) ;
41
+ if ( sum [ cur ] > s ) {
42
+ flag = false ;
43
+ break ;
44
+ } else if ( sum [ cur ] === s ) {
45
+ sum [ cur ] = 0
46
+ }
47
+ for ( const next of g [ cur ] ) {
48
+ if ( visited [ next ] ) continue ;
49
+ sum [ next ] += sum [ cur ] ;
50
+ ind [ next ] -- ;
51
+ if ( ind [ next ] === 1 ) {
52
+ q . push ( next ) ;
53
+ visited [ next ] = true ;
54
+ }
55
+ }
56
+ }
57
+ if ( flag ) return total / s - 1 ;
58
+
59
+ }
60
+ return 0
61
+ } ;
62
+
63
+ // another
64
+
65
+
1
66
/**
2
67
* @param {number[] } nums
3
68
* @param {number[][] } edges
You can’t perform that action at this time.
0 commit comments