Skip to content

Commit 66da5bf

Browse files
committed
Improved task 3367
1 parent 55dea6a commit 66da5bf

File tree

1 file changed

+34
-25
lines changed
  • src/main/kotlin/g3301_3400/s3367_maximize_sum_of_weights_after_edge_removals

1 file changed

+34
-25
lines changed
Lines changed: 34 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,50 @@
11
package g3301_3400.s3367_maximize_sum_of_weights_after_edge_removals
22

3-
// #Hard #2024_11_24_Time_220_ms_(100.00%)_Space_154.5_MB_(100.00%)
3+
// #Hard #2024_11_27_Time_118_ms_(100.00%)_Space_140.5_MB_(100.00%)
44

55
import java.util.PriorityQueue
66
import kotlin.math.max
77

88
class Solution {
9+
private lateinit var adj: Array<MutableList<IntArray>>
10+
private var k = 0
11+
912
fun maximizeSumOfWeights(edges: Array<IntArray>, k: Int): Long {
10-
val map = HashMap<Int?, ArrayList<IntArray>?>()
11-
for (edge in edges) {
12-
map.computeIfAbsent(edge[0]) { _: Int? -> ArrayList<IntArray>() }!!
13-
.add(intArrayOf(edge[1], edge[2]))
14-
map.computeIfAbsent(edge[1]) { _: Int? -> ArrayList<IntArray>() }!!
15-
.add(intArrayOf(edge[0], edge[2]))
13+
val n = edges.size + 1
14+
adj = Array(n) { ArrayList<IntArray>() }
15+
this.k = k
16+
for (i in 0..<n) {
17+
adj[i] = ArrayList<IntArray>()
18+
}
19+
for (e in edges) {
20+
adj[e[0]].add(e)
21+
adj[e[1]].add(e)
1622
}
17-
return maximizeSumOfWeights(0, -1, k, map)[0]
23+
return dfs(0, -1)[1]
1824
}
1925

20-
private fun maximizeSumOfWeights(
21-
v: Int,
22-
from: Int,
23-
k: Int,
24-
map: HashMap<Int?, ArrayList<IntArray>?>,
25-
): LongArray {
26+
private fun dfs(v: Int, parent: Int): LongArray {
2627
var sum: Long = 0
27-
val queue = PriorityQueue<Long>()
28-
for (i in map[v]!!) {
29-
if (i[0] != from) {
30-
val next = maximizeSumOfWeights(i[0], v, k, map)
31-
next[1] += i[1].toLong()
32-
sum = sum + max(next[0], next[1])
33-
if (next[0] < next[1]) {
34-
queue.offer(next[1] - next[0])
35-
sum = sum - (if (queue.size > k) queue.poll() else 0)
36-
}
28+
val pq = PriorityQueue<Long?>()
29+
for (e in adj[v]) {
30+
val w = if (e[0] == v) e[1] else e[0]
31+
if (w == parent) {
32+
continue
3733
}
34+
val res = dfs(w, v)
35+
val max = max((e[2] + res[0]), res[1])
36+
sum += max
37+
pq.add(max - res[1])
38+
}
39+
val res = LongArray(2)
40+
while (pq.size > k) {
41+
sum -= pq.poll()!!
42+
}
43+
res[1] = sum
44+
while (pq.size > k - 1) {
45+
sum -= pq.poll()!!
3846
}
39-
return longArrayOf(sum, sum - (if (queue.size < k) 0 else queue.peek())!!)
47+
res[0] = sum
48+
return res
4049
}
4150
}

0 commit comments

Comments
 (0)