代码之家  ›  专栏  ›  技术社区  ›  zonyang

到达目的地的最小站

  •  1
  • zonyang  · 技术社区  · 8 年前
    Class GasStation {
        int distanceToDestination;
        int availableGas;
    }
    

    给定三个参数 G 表示车辆初始气体量, D 表示到目的地的距离。以及气体状态列表,其中每个气体状态的变量是 距离目的地 第二个是该站的可用煤气。如何计算到达目的地的最小站?

    g = 10 gallon,
    d = 20 miles,
    list of GasStation:
    gasStations = [[15, 1], [14,10], [12,12]].
    

    编辑:没有容量限制。

    1 回复  |  直到 8 年前
        1
  •  2
  •   xashru    8 年前

    既然你没提过,我想你需要 k 加仑的汽油 1 英里。如果总容量不太大,可以通过dp来解决。我概述了一个使用递归和记忆化的解决方案。

    gasStations  = [list of GasStations]
    sort gasStations  by decreasing value of distanceToDestination if its not already sorted
    k : gas required to travel 1 mile
    maxNumberOfGasStation : maximum gas stations possible
    maxPossibleCapacity : maximum gas that might be required for a trip
    memo = [maxNumberOfGasStation][maxPossibleCapacity] filled up with -1
    
    int f(idx, currentGas) {
        if (G[idx].distanceToDestination * k <= current_gas) {
            // You can reach destination using the gas you have left without filling any more
            return 0
        }
        if(idx == gasStations.length - 1) {
            // last station
            if (G[idx].distanceToDestination * k > current_gas + G[idx].availableGas) {
                // You cannot reach destination even if you fill up here
                return INT_MAX
            } else{
                return 1;
            }
        }   
        if(memo[idx][currentGas] != -1) return memo[idx][currentGas];
    
        // option 1: stop at this station
        int distBetweenStation = G[idx].distanceToDestination - G[idx+1].distanceToDestination
        int r1 = 1 + f(idx+1, min(currentGas + G[idx].availableGas, maxPossibleCapacity) - distBetweenStation * k)
    
        // option 2: don't stop at this station
        int r2 = f(idx+1, currentGas - distBetweenStation * k)
    
        // take minimum
        int r = min(r1, r2)
    
        memo[idx][currentGas] = r
        return r;
    }
    

    去接电话 f(0, g - (d - gasStations[0].distanceToDestination) * k) 。时间复杂性是 O(maxNumberOfGasStation * maxPossibleCapacity) . 如果有 capicity 限制您可以简单地替换 maxPossibleCapacity 带着它。