AIRTRAV - Editorial

Problem Link - Chef Airlines Practice Problem in Heaps

Problem Statement

You are a premium member of Chef Airlines which means you can store miles in your Chef Airlines account. If you currently have x miles in your Chef Airlines account then you can travel x miles for free. You start from the airport labelled 0 and wish to reach airport labelled N. Following are the rules of travel :

  • If you are at the airport labelled i, you can travel to any airport labelled j, only if j > i;

  • If you travel from airport labelled i to airport labelled j, you end up exhausting j - i miles from your Chef Airlines account. Consequently, you can travel from airport labelled i to airport labelled j if and only if j - i \leq x, where x is the number of miles in your Chef Airlines account when you departed from the airport labelled i.

  • Whenever you arrive at airport labelled i, you can add up to M_i number of miles in your Chef Airlines account. There is no limit to the number of miles your Chef Airlines account can hold.

  • You start by arriving at airport labelled 1 with 0 miles in your Chef Airlines account.

Determine the minimum number of airports you must visit in order to reach the airport labelled N. If it is not possible to do so, print -1.

Approach

To solve this problem efficiently, we can employ a greedy algorithm combined with a breadth-first search (BFS) approach using a queue.

  1. Initialization:
  • Use a Priority Queue to store the current position (airport index) and the miles in the account.
  • Start from airport 1 with 0 miles and 1 visit.
  1. Traversal:
  • Use BFS to explore reachable airports from the current airport.
  • For each airport i, calculate the maximum distance you can cover based on available miles.
  • For each reachable airport j, if you can travel there (i.e., you have enough miles), update the miles and enqueue the new state.
  1. Stopping Condition:
  • If you reach airport N, output the number of visits.
  • If the queue is exhausted without reaching airport N, return -1.

Complexity

  • Time Complexity: O(N) per test case, as each airport is processed once in the BFS traversal.
  • Space Complexity: O(N) for the queue and visited array.