【问题标题】:minimum stop to get to destination到达目的地的最短停留时间
【发布时间】:2018-05-23 21:36:44
【问题描述】:
Class GasStation {
    int distanceToDestination;
    int availableGas;
}

给定三个参数g代表车辆初始油量,d代表到目的地的距离。以及一个加油站列表,其中每个加油站的变量是 distanceToDestination,第二个是该加油站的可用气体。如何计算到达目的地的最小停靠站?

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

编辑:没有容量限制。

【问题讨论】:

  • 1.您将需要了解车辆的燃油经济性。 2. 这听起来像是推销员问题的一个转折点。
  • 您缺少必需的信息。您提供了 g=gas 容量,这意味着您可以在车辆中使用的最大燃料量。初始气体量是多少?什么是距离燃料比?
  • 你为什么要标记“贪婪”?您只期望贪心算法解决方案吗?
  • @nurdyguy 您指的是哪个“推销员问题”?这当然不像旅行推销员问题。

标签: algorithm dynamic-programming greedy


【解决方案1】:

由于您没有提到它,我假设您需要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 替换为它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2016-10-13
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多