結果
問題 | No.1301 Strange Graph Shortest Path |
ユーザー | yudedako |
提出日時 | 2022-01-11 09:08:44 |
言語 | Kotlin (2.1.0) |
結果 |
AC
|
実行時間 | 1,688 ms / 3,000 ms |
コード長 | 2,675 bytes |
コンパイル時間 | 18,244 ms |
コンパイル使用メモリ | 449,760 KB |
実行使用メモリ | 150,392 KB |
最終ジャッジ日時 | 2024-11-14 11:27:54 |
合計ジャッジ時間 | 66,359 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 33 |
ソースコード
import java.util.* class Edge(val to: Int, val pair: Int, var flow: Boolean, val cost: Long) { override fun toString(): String { return "Edge(to: $to, pair: $pair, flow: $flow, cost: $cost)" } } class MinCostFlow(val size: Int) { val vec = Array(size){ mutableListOf<Edge>()} fun addEdge(from: Int, to: Int, cost: Long) { vec[from].add(Edge(to, vec[to].size, true, cost)) vec[to].add(Edge(from, vec[from].size - 1, false, -cost)) } fun push(source: Int, sink: Int, flowLimit: Int = Int.MAX_VALUE): List<Long> { val potential = LongArray(size) val minDistance = LongArray(size) val queue = PriorityQueue(compareBy(Pair<Int, Long>::second)) val prevEdge = Array(size){Edge(-1, -1, false, -1)} val result = mutableListOf(0L) repeat(flowLimit){ minDistance.fill(Long.MAX_VALUE) minDistance[source] = 0 queue.clear() queue.add(source to 0L) while (queue.isNotEmpty()) { val (current, cost) = queue.poll() if (minDistance[current] < cost) continue for (next in vec[current]) { if (!next.flow) continue val e = potential[current] - potential[next.to] + next.cost if (minDistance[next.to] > cost + e) { minDistance[next.to] = cost + e prevEdge[next.to] = next queue.add(next.to to cost + e) } } } if (minDistance[sink] == Long.MAX_VALUE) return result for (i in minDistance.indices) { potential[i] += minDistance[i] } result.add(result.last() + potential[sink]) var last = sink while (last != source) { val e = prevEdge[last] val r = vec[e.to][e.pair] e.flow = false r.flow = true last = r.to } } return result } } fun main() { val (n, m) = readLine()!!.trim().split(' ').map(String::toInt) val edges = List(m){ val (u, v, c, d) = readLine()!!.trim().split(' ').map(String::toInt) (u - 1 to v - 1) to (c to d) } val graph = MinCostFlow(n) for ((vertices, costs) in edges) { val (u, v) = vertices val (c, d) = costs graph.addEdge(u, v, c.toLong()) graph.addEdge(u, v, d.toLong()) graph.addEdge(v, u, c.toLong()) graph.addEdge(v, u, d.toLong()) } val result = graph.push(0, n - 1, 2)[2] println(result) }