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

📅  最后修改于: 2021-10-28 01:50:13             🧑  作者: Mango

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

例子:

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

  • 初始化一个 HashMap,比如map,来存储车站的索引及其各自的燃料费率。
  • 初始化一个优先队列,比如pq,以存储车站的索引和燃料成本以及正在填充的燃料升数。
  • 初始化两个变量,比如cost,存储所需的最小成本,并设置flag = false以检查是否有任何加油站。
  • 迭代范围[1, N]
    • 检查是否有车站。如果发现为真,则将其插入pq
    • 拆除所有无法加注燃料的加油站。
    • 如果pq为空,则不可能到达行尾。因此,设置flag = true
    • 存储成本最低的站点并更新成本和从该特定站点泵送的升数。
    • 再次将其插入pq
  • 如果标志为真,则打印“-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)