当前位置: 首页 > 知识库问答 >
问题:

加油站动态规划

司马洲
2023-03-14

你和你的朋友开车去提华纳度春假。你在为旅行存钱,所以你想把路上的油费降到最低。为了最小化你的汽油成本,你和你的朋友整理了以下信息。首先,你的汽车可以可靠地行驶m英里的油箱(但没有进一步)。你的一个朋友从网上挖掘了加油站的数据,并绘制了你路线上的每一个加油站,以及该加油站的汽油价格。具体而言,他们创建了一个从最近到最远的n+1个加油站价格列表,以及两个相邻加油站之间的n个距离列表。塔科马是0号加油站,蒂华纳是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;
}

}

共有1个答案

轩辕庆
2023-03-14

站点i的最小再填充成本表示为成本[i]

给出了问题说明,该成本如何表示?
我们知道,每次下一次重新加注必须在距离上次加注170英里的范围内进行,
因此最小成本可以表示如下:

成本[i]=MIN{成本[j]+价格[i]*distance_from_i_to_j}对于每个j,使得距离(i,j)<=170 mi

对于基本情况成本[0]=0如果我们不考虑站0的全部油箱成本,否则基本情况为成本[0]=170*价格[0]

我将假设我们不考虑站0的全部油箱成本,并且在最终点即站19不需要再加注

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

还需要注意的是,由于我们不需要在第19站重新填充,所以我们应该只计算在1站到18站重新填充的成本,即cost[1],cost[2],..,cost[18]。这样做之后,问题的答案将是min{cost[14],cost[15],cost[16],cost[17],cost[18]}因为距离第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];
}
 类似资料:
  • 本文向大家介绍C ++中的最小加油站数,包括了C ++中的最小加油站数的使用技巧和注意事项,需要的朋友参考一下 假设有一辆汽车,从起始位置行驶到距起始位置以东t英里的目的地。 现在,沿途有许多加油站。因此,每个加油站[i]代表加油站,该加油站位于起始位置以东的加油站[i] [0]英里处,并且该加油站的加油站数为[i] [1]升。 如果汽车以无限大的油箱启动,那么最初的油箱中将装有燃油。它每行驶1英

  • 现在,我已经挣扎了几个小时,试图弄清楚如何在我的解决方案中加入记忆。 问题 如何在解决方案中添加工作记忆。在这种情况下,我的错误在哪里? 对于如何添加记忆,是否有经验法则或指导原则。 在上面main内部的示例中,正确的结果是5。我的常规解决方案(没有记忆)打印出5个,但有了记忆,它打印出6个。

  • 问题内容: 我正在考虑减少使用。js(看起来不错),但我们的网站要求在初始页面加载后动态加载某些样式。但是,似乎所有LESS样式表必须在less.js脚本加载之前先加载。即这有效 但是如果换行,它将失败,除非正确订购,否则Firefox和chrome都不会尝试加载“style.less”。在本教程中明确指出了订购要求。 有什么方法可以在初始页面加载后加载更少的样式表? - 保存您的LESS代码时,

  • 计算机科学中的许多程序是为了优化一些值而编写的; 例如,找到两个点之间的最短路径,找到最适合一组点的线,或找到满足某些标准的最小对象集。计算机科学家使用许多策略来解决这些问题。本书的目标之一是向你展示几种不同的解决问题的策略。动态规划 是这些类型的优化问题的一个策略。 优化问题的典型例子包括使用最少的硬币找零。假设你是一个自动售货机制造商的程序员。你的公司希望通过给每个交易最少硬币来简化工作。假设

  • *正则匹配问题[H] 三角形问题[M] 计算二进制数中1的个数[M] *括号匹配问题[M] 最短路径和[M]

  • 规则 Sentinel 的理念是开发者只需要关注资源的定义,当资源定义成功后可以动态增加各种流控降级规则。Sentinel 提供两种方式修改规则: 通过 API 直接修改 (loadRules) 通过 DataSource 适配不同数据源修改 手动通过 API 修改比较直观,可以通过以下几个 API 修改不同的规则: FlowRuleManager.loadRules(List<FlowRule>