首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >加油站动态规划

加油站动态规划
EN

Stack Overflow用户
提问于 2018-11-18 04:46:35
回答 1查看 10.8K关注 0票数 4

你和你的朋友们正开车去提华纳度假。你在为旅行省钱,所以你想在路上尽量减少汽油的费用。为了将你的汽油成本降到最低,你和你的朋友们汇编了以下信息。首先,你的车可以可靠地在一罐汽油上行驶数百英里(但不能再行驶了)。你的一个朋友已经从网络上挖掘了加油站的数据,并在你的路线上绘制了每一个加油站,以及加油站的汽油价格。Specifi,他们创建了一个从最近到最远的fi加油站价格列表,以及相邻两个加油站之间的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

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

代码语言:javascript
复制
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;
}

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-20 06:48:25

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) <= 170 mi

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

我将假设我们不考虑station 0的全部油箱成本,而且在最后一点,即station 19,不需要再加油。

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

还要注意的是,由于我们不需要在station 19加注,所以我们应该计算仅通过18 (即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站。

在用基本情况定义了上述递归关系之后,我们可以通过以下方式将其转换为循环:

代码语言:javascript
复制
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];
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53357989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档