File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } edges
3
+ * @param {number } bob
4
+ * @param {number[] } amount
5
+ * @return {number }
6
+ */
7
+ const mostProfitablePath = function ( edges , bob , amount ) {
8
+ const graph = [ ] , depth = [ ] , parent = [ ]
9
+ for ( const [ u , v ] of edges ) {
10
+ if ( graph [ u ] == null ) graph [ u ] = [ ]
11
+ if ( graph [ v ] == null ) graph [ v ] = [ ]
12
+ graph [ u ] . push ( v )
13
+ graph [ v ] . push ( u )
14
+ }
15
+ dfs ( 0 )
16
+ let cur = bob , bobh = 0
17
+ while ( cur ) {
18
+ if ( depth [ cur ] > bobh ) amount [ cur ] = 0
19
+ else if ( depth [ cur ] === bobh ) amount [ cur ] /= 2
20
+
21
+ bobh ++
22
+ cur = parent [ cur ]
23
+ }
24
+
25
+ // console.log(depth, parent, amount)
26
+
27
+ return dfs2 ( 0 )
28
+
29
+ function dfs ( node , p = 0 , d = 0 ) {
30
+ parent [ node ] = p
31
+ depth [ node ] = d
32
+ for ( const e of graph [ node ] ) {
33
+ if ( e === p ) continue
34
+ dfs ( e , node , d + 1 )
35
+ }
36
+ }
37
+
38
+ function dfs2 ( node , p = 0 ) {
39
+ let res = amount [ node ]
40
+ let ma = - Infinity
41
+ for ( const e of graph [ node ] ) {
42
+ if ( e === p ) continue
43
+ ma = Math . max ( ma , dfs2 ( e , node ) )
44
+ }
45
+ if ( ma === - Infinity ) return res
46
+ return res + ma
47
+ }
48
+ } ;
You can’t perform that action at this time.
0 commit comments