【问题标题】:Gas Station Dynamic Programming加油站动态规划
【发布时间】:2018-11-18 04:46:35
【问题描述】:

你和你的朋友正开车去提华纳过春假。您正在为旅行省钱,因此您希望将途中的汽油成本降至最低。为了尽量减少您和您的朋友的汽油成本,您和您的朋友整理了以下信息。首先,您的汽车可以在油箱上可靠地行驶 m 英里(但不能再进一步)。您的一个朋友从网上挖掘了加油站数据,并绘制了您路线上的每个加油站以及该加油站的汽油价格。具体来说,他们创建了从最近到最远的 n+1 个加油站价格列表以及两个相邻加油站之间的 n 个距离列表。 Tacoma 是 0 号加油站,Tijuana 是 n 号加油站。为方便起见,他们已将汽油成本转换为您汽车行驶的每英里价格。此外,还计算了两个相邻加油站之间的英里距离。您将以一箱油开始您的旅程,当您到达蒂华纳时,您将为回程加油。您需要确定在哪些加油站停留,以尽量减少旅途中的汽油费用。

示例输入:

价格(每英里美分) [12,14,21,14,17,22,11,16,17,12,30,25,27,24,22,15,24,23,15,21]

距离(英里) [31,42,31,33,12,34,55,25,34,64,24,13,52,33,23,64,43,25,15]

您的汽车一罐油可以行驶 170 英里。

我的输出:

旅行的最低费用为:117.35 美元

加油站停靠:[1, 6, 9, 13, 17, 19]

我已经解决了这个问题,但我不确定我是否以正确的方式解决了问题。如果错了,有人能给我一些建议或指出正确的方向吗?提前谢谢你。

public class GasStation {

/** An array of gas prices.*/
private int[] myPrice;
/** An array of distance between two adjacent gas station.*/
private int[] myDistance;
/** Car's tank capacity.*/
private int myCapacity;
/** List of gas stations to stop at to minimize the cost.*/
private List<Integer> myGasStations;


/**
 * A constructor that takes in a price list, distance list, and the car's tank capacity.
 * @param thePrice - price list
 * @param theDistance - distance list
 * @param theCapacity - the car's capacity
 */
public GasStation(final int[] thePrice, final int[] theDistance,
        final int theCapacity) {
    myPrice = thePrice;
    myDistance = theDistance;
    myCapacity = theCapacity;
    myGasStations = new ArrayList<>();
}


/**
 * Calculate for the minimum cost for your trip.
 * @return minimum cost
 */
public int calculateMinCost() {

    int lenP = myPrice.length;
    int lenD = myDistance.length;
    if (lenP == 0 || lenD == 0 || myCapacity == 0) return 0;

    // gas station -> another gas station (moves) 
    Map<Integer, Integer> gasD = new HashMap<>();
    int[] D = new int[lenD + 1];
    D[0] = 0;

    // calculate the total distance 
    for (int i = 0; i < lenD; i++) {
        D[i + 1] = D[i] + myDistance[i];
    }

    int len = D.length;
    for (int i = 1; i < len - 1; i++) {
        int j = len - 1;
        while (D[j] - D[i] >= myCapacity) {
            j--;
        }
        gasD.put(i, j - i);
    }

    int min = Integer.MAX_VALUE;

    for (int i = 1; i < len; i++) {
        int temp = 0;
        int cur = i;
        List<Integer> tempList = new ArrayList<>();
        if (D[i] <= myCapacity) {
            temp = D[cur] * myPrice[cur];
            tempList.add(cur);
            int next = gasD.get(cur) + cur;
            while (next < len) {
                temp += (D[next] - D[cur]) * myPrice[next];
                cur = next;
                tempList.add(cur);
                if (gasD.containsKey(cur)) next = gasD.get(cur) + cur;
                else break;
            }

            if (temp < min) {
                min = temp;
                myGasStations = tempList;
            }

        }
    }


    return min;
}

/**
 * Get gas stations to stop at.
 * @return a list of gas stations to stop at
 */
public List<Integer> getGasStations() {
    return myGasStations;
}

}

【问题讨论】:

  • 它看起来太长了,在我看来它要简单得多。那么从塔科马到蒂华纳的单程旅行,你得到了11735 cents 的总费用吗?我得到了7489 cents 并在加油站停下来[1, 6, 9, 11, 15, 19]
  • 补充31 milesstation 114 cents/mi,补充152 milesstation 611 cents/mi,补充114 milesstation 9@9876754333@9876754333 @@station 1125 cents/mi121 milesstation 1515 cents/mi,最后到达station 19
  • 总费用为(31 * 14) + (152 * 11) + (114 * 12) + (88 * 25) + (121 * 15) = 7489 cents。我假设我们不需要在station 0(起点)计算满罐(即170 * 12)的成本。好吧,就算我算上,成本还是比你少。如果你好奇,我可以用我使用的方法在下面回复
  • 如果我们在station 19补充回程,费用为147 mi * 21 cents/mi3087,总费用为7489 + 3087 = 10576,再次低于您的结果
  • 你是对的!从那时起,我对我的代码进行了更改,我得到了更好的成本,但它仍然不是像你得到的结果那样的最佳解决方案。您是否建议我的代码中的某个部分修复并改进算法?谢谢!

标签: java dynamic-programming


【解决方案1】:

station i 的最低充值成本记为cost[i]

给定问题陈述,如何表达这个成本?
我们知道,每次下一次充值都必须在距离上一次充值的170 miles 内完成,
所以最小成本可以表示为:

cost[i] = MIN { cost[j] + price[i] * distance_from_i_to_j } for every j such that distance(i,j) &lt;= 170 mi

如果我们不考虑station 0 的全油箱成本,则使用基本情况cost[0] = 0,否则基本情况为cost[0]= 170 * price[0]

我会假设我们不考虑station 0 处的全部油箱成本,并且在最后一点(即station 19)不需要重新填充

通过查看上面定义的递归关系,我们很容易注意到同一个子问题被多次调用,这意味着我们可以利用动态规划解决方案来避免可能的指数运行时间。

还要注意,由于我们不需要在station 19 加油,我们应该只计算在118 的加油站的加油成本,即cost[1], cost[2], .., cost[18]。这样做之后,问题的答案将是MIN { cost[14], cost[15], cost[16], cost[17], cost[18] },因为距离station 19 170 英里范围内的唯一车站是14,15,16,17,18 车站,因此我们可以通过在这 5 个车站中的一个加油站到达19 车站。

在我们定义了上述与base case的递归关系后,我们可以通过以下方式将其转换为循环:

int price[] =  {12,14,21,14,17,22,11,16,17,12,30,25,27,24,22,15,24,23,15,21}; //total 20 stations

int distance[] = {31,42,31,33,12,34,55,25,34,64,24,13,52,33,23,64,43,25,15};  //total 19 distances      

int N=19;
int[] cost = new int[N];    
int[] parent = new int[N]; //for backtracking

cost[0] = 0; //base case (assume that we don't need to fill gas on station 0)

int i,j,dist;
int maxroad = 170;

for(i=0; i<N; i++) //initialize backtracking array
    parent[i] = -1;


for(i=1; i<=N-1; i++) //for every station from 1 to 18
{

        int priceval = price[i]; //get price of station i               
        int min = Integer.MAX_VALUE;                
        dist = 0;            

        for(j=i-1; j>=0; j--) //for every station j within 170 away from station i
        {   
            dist += distance[j]; //distance[j] is distance from station j to station j+1
            if(dist>maxroad)
               break;   

            if((cost[j] + priceval*dist)<min) //pick MIN value defined in recurrence relation                       
               {
                min = cost[j] + priceval*dist;
                parent[i] = j;
               }

        }

        cost[i] = min;              

}


//after all costs from cost[1] up to cost[18] are found, we pick
//minimum cost among the stations within 170 miles away from station 19
//and show the stations we stopped at by backtracking from end to start

int startback=N-1;
int answer=Integer.MAX_VALUE;
i=N-1;
dist=distance[i];
while(dist<=maxroad && i>=0)
{
   if(cost[i]<answer)
      {
       answer = cost[i];
       startback=i;
      }  
   i--;
   dist += distance[i];
}


System.out.println("minimal cost=" + answer + "\nbacktrack:");

i=startback;
while(i>-1) //backtrack
{
    System.out.println(i + " ");
    i = parent[i];
}

【讨论】:

  • 非常感谢您的解决方案。我已经使用最短路径算法解决了这个问题,但我会尝试你的解决方案,看看我是否得到相同的结果。
  • @mangusta 很好的解决方案。但我很困惑。假设 i 是 5,j 是 3,那么对于 cost[5] 的最小值,我们将 cost[3] + (dist b/w 3-5 * price[5]) 作为候选。但是在 5 站购买燃料的价格,永远不会用于从 5 到 3,因为我们正在向 19 站前进,所以无论我在 5 购买什么,都将用于前往 6,7 站, 8...那么这种方法是如何工作的?基本上,当燃料用于大于 i 的索引时,为什么我们要通过与先前站点 (0
  • @JohnDoe cost[5] 仅反映达到 5 的成本 而不是更进一步,它不包括达到 6、7、8 等的成本。另一方面,6、7、8 的成本可能(或可能不)包括到达 5 的成本,而这又可能(或可能不)包括到达 1、2、3、4 的成本。这只是一个递归
  • @mangusta 非常感谢您的回复:),你说的很有道理,我有点慢。我仍然有些困惑,假设 5 和 3 之间的距离是 10 英里,价格 [5] 是 8,那么您在其中一个候选者中也添加 8*10 以获得最低成本 [5],这个因素是 80当我永远不会以 8 的价格覆盖这 10 英里时,最终导致正确答案,因为价格在第五站是 8,而这个 8*10 是在 5 站之前 10 英里。请帮忙解释。我在想,假设在 3 号站我的费用是 250,而 5 号站是 10 英里,然后再充值 10*price[3] 以达到 5
  • @JohnDoe 在从ji 的旅途中,汽车消耗了相当于distance_from_i_to_j 的一定量的汽油,在i 加油站为price[i] 加油。我们从可能的选项中选择最便宜的补充(即距离i 170 英里范围内的加油站)
猜你喜欢
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
  • 2019-01-14
相关资源
最近更新 更多