|
1 | 1 | package g3301_3400.s3367_maximize_sum_of_weights_after_edge_removals |
2 | 2 |
|
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%) |
4 | 4 |
|
5 | 5 | import java.util.PriorityQueue |
6 | 6 | import kotlin.math.max |
7 | 7 |
|
8 | 8 | class Solution { |
| 9 | + private lateinit var adj: Array<MutableList<IntArray>> |
| 10 | + private var k = 0 |
| 11 | + |
9 | 12 | 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) |
16 | 22 | } |
17 | | - return maximizeSumOfWeights(0, -1, k, map)[0] |
| 23 | + return dfs(0, -1)[1] |
18 | 24 | } |
19 | 25 |
|
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 { |
26 | 27 | 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 |
37 | 33 | } |
| 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()!! |
38 | 46 | } |
39 | | - return longArrayOf(sum, sum - (if (queue.size < k) 0 else queue.peek())!!) |
| 47 | + res[0] = sum |
| 48 | + return res |
40 | 49 | } |
41 | 50 | } |
0 commit comments