📌  相关文章
📜  最小化到达N长度直线路径末端的成本

📅  最后修改于: 2021-04-17 14:32:27             🧑  作者: Mango

给定一个整数K,该整数K表示在长度为N米的直线路径上行驶的汽车的燃料容量为1升/公吨,并具有两个数组a []b [],每个数组的大小为M,其中a [i]表示第i加油站的位置, b [i]表示在该加油站1升燃料的成本。任务是找到从0开始到行尾所需的最低成本。如果无法到达终点,则打印-1

例子:

方法:想法是使用Priority Queue和HashMap来存储加油站,以便以最低的成本获得加油站。请按照以下步骤解决问题:

  • 初始化一个HashMap(例如地图),以存储车站的索引及其各自的燃油消耗率。
  • 初始化一个优先队列,例如pq,以存储加油站的索引,燃料成本以及所加燃料的升数。
  • 初始化两个变量,例如cost,以存储所需的最低成本,并设置flag = false来检查是否有加油站。
  • 迭代范围[1,N]
    • 检查是否有电台。如果发现是真的,则将其插入pq
    • 移开所有无法加油的站。
    • 如果pq为空,则不可能到达行尾。因此,将flag设置为true
    • 存储成本最低的站点,并更新成本和从该特定站点泵出的升数。
    • 再次将其插入pq
  • 如果标志为true,则打印“ -1”。这意味着没有加油站。因此,不可能到达行尾。
  • 否则,打印最低成本以达到该行的末尾。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// For priority_queue
struct Compare {
  bool operator()(array a, array b)
  {
    return a[1] > b[1];
  }
};
 
// Function to calculate the minimum cost
// required to reach the end of Line
void minCost(int N, int K, int M, int a[], int b[])
{
  // Checks if possible to
  // reach end or not
  bool flag = true;
 
  // Stores the stations and
  // respective rate of fuel
  unordered_map map;
  for (int i = 0; i < M; i++) {
    map[a[i]] = b[i];
    if (i == M - 1 && K < N - a[i]) {
      flag = false;
      break;
    }
    else if (i < M - 1 && K < a[i + 1] - a[i]) {
      flag = false;
      break;
    }
  }
 
  if (!flag) {
    cout << -1;
    return;
  }
 
  // Stores the station index and cost of fuel and
  // litres of petrol which is being fueled
  priority_queue, vector >,
  Compare>
    pq;
  int cost = 0;
  flag = false;
 
  // Iterate through the entire line
  for (int i = 0; i < N; i++) {
 
    // Check if there is a station at current index
    if (map.find(i) != map.end()) {
      array arr = { i, map[i], 0 };
      pq.push(arr);
    }
 
    // Remove all the stations where
    // fuel cannot be pumped
    while (pq.size() > 0 && pq.top()[2] == K)
      pq.pop();
 
    // If there is no station left to fill fuel
    // in tank, it is not possible to reach end
    if (pq.size() == 0) {
      flag = true;
      break;
    }
 
    // Stores the best station
    // visited so far
    array best_bunk = pq.top();
    pq.pop();
 
    // Pump fuel from the best station
    cost += best_bunk[1];
 
    // Update the count of litres
    // taken from that station
    best_bunk[2]++;
 
    // Update the bunk in queue
    pq.push(best_bunk);
  }
  if (flag) {
    cout << -1 << "\n";
    return;
  }
 
  // Print the cost
  cout << cost << "\n";
}
 
// Driven Program
int main()
{
 
  // Given value of N, K & M
  int N = 10, K = 3, M = 4;
 
  // Given arrays
  int a[] = { 0, 1, 4, 6 };
  int b[] = { 5, 2, 2, 4 };
 
  // Function call to calculate minimum
  // cost to reach end of the line
  minCost(N, K, M, a, b);
 
  return 0;
}
 
// This code is contributed by Kingash.


Java
// Java program for the above approach
 
import java.util.*;
public class Main {
 
    // Function to calculate the minimum cost
    // required to reach the end of Line
    static void minCost(int N, int K, int M,
                        int[] a, int[] b)
    {
        // Checks if possible to
        // reach end or not
        boolean flag = true;
 
        // Stores the stations and
        // respective rate of fuel
        HashMap map = new HashMap<>();
        for (int i = 0; i < M; i++) {
            map.put(a[i], b[i]);
            if (i == M - 1 && K < N - a[i]) {
                flag = false;
                break;
            }
            else if (i < M - 1 && K < a[i + 1] - a[i]) {
                flag = false;
                break;
            }
        }
 
        if (!flag) {
            System.out.println("-1");
            return;
        }
 
        // Stores the station index and cost of fuel and
        // litres of petrol which is being fueled
        PriorityQueue pq
            = new PriorityQueue<>((c, d) -> c[1] - d[1]);
        int cost = 0;
        flag = false;
 
        // Iterate through the entire line
        for (int i = 0; i < N; i++) {
 
            // Check if there is a station at current index
            if (map.containsKey(i))
                pq.add(new int[] { i, map.get(i), 0 });
 
            // Remove all the stations where
            // fuel cannot be pumped
            while (pq.size() > 0 && pq.peek()[2] == K)
                pq.poll();
 
            // If there is no station left to fill fuel
            // in tank, it is not possible to reach end
            if (pq.size() == 0) {
                flag = true;
                break;
            }
 
            // Stores the best station
            // visited so far
            int best_bunk[] = pq.poll();
 
            // Pump fuel from the best station
            cost += best_bunk[1];
 
            // Update the count of litres
            // taken from that station
            best_bunk[2]++;
 
            // Update the bunk in queue
            pq.add(best_bunk);
        }
        if (flag) {
            System.out.println("-1");
            return;
        }
 
        // Print the cost
        System.out.println(cost);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Given value of N, K & M
        int N = 10, K = 3, M = 4;
 
        // Given arrays
        int a[] = { 0, 1, 4, 6 };
        int b[] = { 5, 2, 2, 4 };
 
        // Function call to calculate minimum
        // cost to reach end of the line
        minCost(N, K, M, a, b);
    }
}


输出:
-1

时间复杂度: O(N * logN)
辅助空间: O(N)