[白駿1939-Kotlin]重量制限


質問リンク
  • Binary Searchのターゲットを重みとしてBFSを使用してすべての島を巡回し、ソース島からターゲット島への経路があるかどうか、および検索重みで検索可能な経路があるかどうかを決定します.
  • import java.io.BufferedReader
    import java.io.BufferedWriter
    import java.util.*
    
    data class Bridge(val destination: Int, val weight: Int)
    
    private lateinit var bufferedReader: BufferedReader
    private lateinit var bufferedWriter: BufferedWriter
    private lateinit var bridges: Array<MutableList<Bridge>>
    
    fun main() {
        bufferedReader = System.`in`.bufferedReader()
        bufferedWriter = System.out.bufferedWriter()
    
        // 1. get n, m
        val (n, m) = bufferedReader
            .readLine()
            .split(" ")
            .map { it.toInt() }
    
        // 2. get bridge information
        bridges = Array(n + 1) { mutableListOf() }
        var maxWeight = 0
        repeat(m) {
            val (a, b, c) = bufferedReader
                .readLine()
                .split(" ")
                .map { it.toInt() }
            bridges[a].add(Bridge(b, c))
            bridges[b].add(Bridge(a, c))
    
            // 3. get max weight
            if (maxWeight < c) maxWeight = c
        }
    
        // 4. get factories
        val (factory1, factory2) = bufferedReader
            .readLine()
            .split(" ")
            .map { it.toInt() }
    
    
        // 5. possible weight binary search
        var start = 0
        var end = maxWeight
    
        while (start <= end) {
            val mid = (start + end) / 2
            if (isPossibleWeight(n, factory1, factory2, mid)) start = mid + 1
            else end = mid - 1
        }
        bufferedWriter.write("$end")
    
        bufferedReader.close()
        bufferedWriter.close()
    }
    
    fun isPossibleWeight(n: Int, source: Int, destination: Int, targetWeight: Int): Boolean {
        val queue: Queue<Int> = LinkedList()
        val visited = Array(n + 1) { false }
        queue.add(source)
        visited[source] = true
    
        while (queue.isNotEmpty()) {
            val currDestination = queue.poll()
            if (currDestination == destination) return true
    
            for (nextIsLand in bridges[currDestination]) {
                if (!visited[nextIsLand.destination] && nextIsLand.weight >= targetWeight) {
                    queue.add(nextIsLand.destination)
                    visited[nextIsLand.destination] = true
                }
            }
        }
        return false
    }