11package com.github.contest.graph
22
3+ import java.util.Arrays
34import java.util.LinkedList
5+ import kotlin.math.max
6+
47
58/* *
69 * 997. Find the Town Judge
@@ -64,4 +67,85 @@ fun findCenter(edges: Array<IntArray>): Int {
6467 a == c || a == d -> a
6568 else -> b
6669 }
67- }
70+ }
71+
72+ /* *
73+ * 2467. Most Profitable Path in a Tree
74+ */
75+
76+
77+ fun mostProfitablePath (edges : Array <IntArray >, bob : Int , amount : IntArray ): Int {
78+ val graph = Array (amount.size) { mutableListOf<Int >() }
79+ for (edge in edges) {
80+ graph[edge[0 ]].add(edge[1 ])
81+ graph[edge[1 ]].add(edge[0 ])
82+ }
83+
84+ val bobPath = IntArray (amount.size)
85+ Arrays .fill(bobPath, - 1 )
86+ val path = ArrayList <Int >()
87+ fillBobPath(bob, - 1 , path, graph)
88+
89+ for (i in path.indices) {
90+ bobPath[path[i]] = i
91+ }
92+
93+ return getAliceMaxScore(0 , - 1 , 0 , bobPath, graph, 0 , amount)
94+ }
95+
96+ private fun fillBobPath (
97+ node : Int ,
98+ parentNode : Int ,
99+ path : ArrayList <Int >,
100+ graph : Array <MutableList <Int >>
101+ ): Boolean {
102+ if (node == 0 ) return true
103+ for (neighborNode in graph[node]) {
104+ if (neighborNode != parentNode) {
105+ path.add(node)
106+ if (fillBobPath(neighborNode, node, path, graph)) return true
107+ path.removeAt(path.size - 1 )
108+ }
109+ }
110+ return false
111+ }
112+
113+ private fun getAliceMaxScore (
114+ node : Int ,
115+ parentNode : Int ,
116+ currScore : Int ,
117+ bobPath : IntArray ,
118+ graph : Array <MutableList <Int >>,
119+ timestamp : Int ,
120+ amount : IntArray
121+ ): Int {
122+ var currScore = currScore
123+ if (bobPath[node] == - 1 || bobPath[node] > timestamp) {
124+ currScore + = amount[node]
125+ } else if (bobPath[node] == timestamp) {
126+ currScore + = amount[node] / 2
127+ }
128+ if (graph[node].size == 1 && node != 0 ) return currScore
129+ var maxScore = Int .MIN_VALUE
130+ for (neighborNode in graph[node]) {
131+ if (neighborNode != parentNode) {
132+ maxScore = max(
133+ maxScore.toDouble(),
134+ getAliceMaxScore(
135+ neighborNode,
136+ node,
137+ currScore,
138+ bobPath,
139+ graph,
140+ timestamp + 1 ,
141+ amount
142+ ).toDouble()
143+ )
144+ .toInt()
145+ }
146+ }
147+ return maxScore
148+ }
149+
150+
151+
0 commit comments