LeetCode in Kotlin

2477. Minimum Fuel Cost to Report to the Capital

Medium

There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.

There is a meeting for the representatives of each city. The meeting is in the capital city.

There is a car in each city. You are given an integer seats that indicates the number of seats in each car.

A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.

Return the minimum number of liters of fuel to reach the capital city.

Example 1:

Input: roads = [[0,1],[0,2],[0,3]], seats = 5

Output: 3

Explanation:

It costs 3 liters of fuel at minimum. It can be proven that 3 is the minimum number of liters of fuel needed.

Example 2:

Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2

Output: 7

Explanation:

It costs 7 liters of fuel at minimum. It can be proven that 7 is the minimum number of liters of fuel needed.

Example 3:

Input: roads = [], seats = 1

Output: 0

Explanation: No representatives need to travel to the capital city.

Constraints:

Solution

class Solution {
    private var ans = 0L

    fun minimumFuelCost(roads: Array<IntArray>, seats: Int): Long {
        val adj = ArrayList<ArrayList<Int>>()
        val n = roads.size + 1
        ans = 0L
        for (i in 0 until n) {
            adj.add(ArrayList())
        }
        for (a in roads) {
            adj[a[0]].add(a[1])
            adj[a[1]].add(a[0])
        }
        solve(adj, seats, 0, -1)
        return ans
    }

    private fun solve(adj: ArrayList<ArrayList<Int>>, seats: Int, src: Int, parent: Int): Long {
        var people = 1L
        for (i in adj[src]) {
            if (i != parent) {
                people += solve(adj, seats, i, src)
            }
        }
        if (src != 0) {
            ans += Math.ceil(people.toDouble() / seats).toLong()
        }
        return people
    }
}