Open In App

Find the Platform at which the given Train arrives

Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D array arr[][3] consisting of information of N trains where arr[i][0] is the train number, arr[i][1] is the arrival time, and arr[i][2] is the duration of stoppage time. Given another integer F representing the train number, the task is to find the platform number on which the train with train number F arrives according to the following rules:

  • Platform numbering starts from 1 and there is an infinite number of platforms.
  • The platform which is freed earlier is allocated to the next train.
  • If two or more platforms are freed at the same time then the train arrives at the platform with the lowest platform number.
  • If two or more trains arriving at the same time, then the train with a smaller train number is allocated first.

Examples:

Input: arr[] = {{112567, 1, 2}, {112563, 3, 3}, {112569, 4, 7}, {112560, 9, 3}}, F = 112569
Output: 1
Explanation:
Below is the order of the arrival of trains:
Train          Platform   Leaving Time
112567        1               4
112563        2               7
112569       1              12
112560       2              13

Therefore, the train with train number 112569 arrives at platform number 1.

Input: arr[] = {{112567, 2, 1}, {112563, 5, 5}, {112569, 7, 3}, {112560, 3, 7}}, F = 112569
Output: 3

Approach: The given problem can be solved by using the priority queue. Follow the steps below to solve this problem:

  • Sort the given array arr[] of N trains according to the arrival time of the trains.
  • Initialize a priority queue, say PQ of pairs {PlatformNumber, time} that implements the min-heap according to the least departure time. Insert the {platform number, time} i.e., {1, 0} in the priority queue.
  • Initialize a HashMap, say M that stores the platform number on which any train arrives.
  • Traverse the given array arr[] and perform the following steps:
    • Pop the top platform of the PQ and store them in free_platform[].
    • If the arrival time of the current train is at least the departure time of the popped platform, then update the departure time of the popped platform as the (sum of the arrival and the stoppage time + 1) and insert the current status of the platform in PQ and the current platform number of the current train in the HashMap M.
    • Otherwise, add the new platform entry to the PQ and the current platform number of the current train in the HashMap M.
  • After completing the above steps, print the platform number associated with the train number F in the HashMap M.

Below is the implementation of the above approach: 

C++




#include <bits/stdc++.h>
using namespace std;
 
// Stores the information for each
// train as Objects
class Train {
  public:
  // Stores the train number
 
  string train_num;
 
  // Stores the arrival time
 
  int arrival_time;
 
  // Stores the stoppage time
 
  int stoppage_time;
 
  // Constructor
 
  Train(string train_num, int arrival_time, int stoppage_time) {
    this->train_num = train_num;
    this->arrival_time = arrival_time;
    this->stoppage_time = stoppage_time;
  }
};
 
// custom search comparator
bool sortArrivalTime(Train &o1, Train &o2) {
  if (o1.arrival_time == o2.arrival_time) return o1.train_num < o2.train_num;
  return (o1.arrival_time < o2.arrival_time);
}
 
// Function to find the platform
// on which train F arrives
static int findPlatformOf(vector<Train> trains, int n, string F) {
  // Sort the array arr[] according
  // to the arrival time
 
  sort(trains.begin(), trains.end(), sortArrivalTime);
 
  // Stores the platforms that
  // is in currently in use
  priority_queue<vector<int>> pq;
 
 
  // Insert the platform number 1
  // with departure time as 0
  vector<int> temp = {1, 0};
  pq.push(temp);
 
  // Store the platform number
  // on which train arrived
  map<string, int> schedule;
 
  // Traverse the given array
  for (auto t : trains) {
    // Pop the top platform of
    // the priority queue
    vector<int> free_platform = pq.top();
    pq.pop();
 
    // If arrival time of the train
    // >= freeing time of the platform
    if (t.arrival_time >= free_platform[1]) {
      // Update the train status
      free_platform[1] = t.arrival_time + t.stoppage_time + 1;
      // Add the current platform
      // to the pq
      pq.push(free_platform);
 
      // Add the platform
      // number to the HashMap
      schedule[t.train_num] = free_platform[0];
    }
    // Otherwise, add a new platform
    // for the current train
    else {
      // Update the priority queue
      pq.push(free_platform);
 
      // Get the platform number
      int platform_num = pq.size() + 1;
 
      // Add the platform to
      // the priority queue
      vector<int> temp = {platform_num, t.arrival_time + t.stoppage_time + 1};
      pq.push(temp);
 
      // Add the platform
      // number to the HashMap
      schedule[t.train_num] = platform_num;
    }
  }
 
  // Return the platform on
  // which F train arrived
  return schedule[F];
}
 
// Driver Code
signed main() {
  vector<Train> trains;
 
  trains.push_back(Train("112567", 2, 1));
  trains.push_back(Train("112569", 5, 5));
  trains.push_back(Train("112563", 5, 3));
  trains.push_back(Train("112560", 3, 7));
  string F = "112563";
 
  cout << (findPlatformOf(trains, trains.size(), F));
  return 0;
}
 
// This code is contributed by sdeadityasharma.


Java




// Java program for the above approach
 
import java.util.*;
 
// Stores the information for each
// train as Objects
class Train {
    // Stores the train number
    String train_num;
 
    // Stores the arrival time
    int arrival_time;
 
    // Stores the stoppage time
    int stoppage_time;
 
    // Constructor
    Train(String train_num,
        int arrival_time,
        int stoppage_time)
    {
        this.train_num = train_num;
        this.arrival_time = arrival_time;
        this.stoppage_time = stoppage_time;
    }
}
 
public class GFG {
    // Function to find the platform
    // on which train F arrives
    static int findPlatformOf(
        ArrayList<Train> trains, int n,
        String F)
    {
        // Sort the array arr[] according
        // to the arrival time
        Collections.sort(
            trains,
            (a, b) -> a.arrival_time==b.arrival_time ? Integer.parseInt(a.train_num)-Integer.parseInt(b.train_num) : a.arrival_time - b.arrival_time);
 
        // Stores the platforms that
        // is in currently in use
        PriorityQueue<int[]> pq
            = new PriorityQueue<>(
                (a, b)
                    -> a[1] == b[1] ? a[0] - b[0]
                                    : a[1] - b[1]);
 
        // Insert the platform number 1
        // with departure time as 0
        pq.add(new int[] { 1, 0 });
 
        // Store the platform number
        // on which train arrived
        HashMap<String, Integer> schedule
            = new HashMap<>();
 
        // Traverse the given array
        for (Train t : trains) {
 
            // Pop the top platform of
            // the priority queue
            int[] free_platform = pq.poll();
 
            // If arrival time of the train
            // >= freeing time of the platform
            if (t.arrival_time >= free_platform[1]) {
                // Update the train status
                free_platform[1]
                    = t.arrival_time + t.stoppage_time + 1;
 
                // Add the current platform
                // to the pq
                pq.add(free_platform);
 
                // Add the platform
                // number to the HashMap
                schedule.put(t.train_num,
                            free_platform[0]);
            }
 
            // Otherwise, add a new platform
            // for the current train
            else {
 
                // Update the priority queue
                pq.add(free_platform);
 
                // Get the platform number
                int platform_num = pq.size() + 1;
 
                // Add the platform to
                // the priority queue
                pq.add(new int[] {
                    platform_num,
                    t.arrival_time
                        + t.stoppage_time + 1 });
 
                // Add the platform
                // number to the HashMap
                schedule.put(t.train_num,
                            platform_num);
            }
        }
 
        // Return the platform on
        // which F train arrived
        return schedule.get(F);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        ArrayList<Train> trains
            = new ArrayList<>();
 
        trains.add(new Train(
 
            "112567", 2, 1));
        trains.add(new Train(
            "112569", 5, 5));
        trains.add(new Train(
            "112563", 5, 3));
        trains.add(new Train(
            "112560", 3, 7));
        String F = "112563";
 
        System.out.println(
            findPlatformOf(
                trains, trains.size(), F));
    }
}


Python3




from queue import PriorityQueue
 
# Stores the information for each
# train as Objects
class Train:
    def __init__(self, train_num, arrival_time, stoppage_time):
        # Stores the train number
        self.train_num = train_num
        # Stores the arrival time
        self.arrival_time = arrival_time
        # Stores the stoppage time
        self.stoppage_time = stoppage_time
 
# custom search comparator
def sortArrivalTime(train):
    return (train.arrival_time, train.train_num)
 
# Function to find the platform
# on which train F arrives
def findPlatformOf(trains, n, F):
    # Sort the array arr[] according
    # to the arrival time
    trains.sort(key=sortArrivalTime)
 
    # Stores the platforms that
    # is in currently in use
    pq = PriorityQueue()
 
    # Insert the platform number 1
    # with departure time as 0
    temp = [1, 0]
    pq.put((-temp[1], temp))
 
    # Store the platform number
    # on which train arrived
    schedule = {}
 
    # Traverse the given array
    for t in trains:
        # Pop the top platform of
        # the priority queue
        free_platform = pq.get()[1]
 
        # If arrival time of the train
        # >= freeing time of the platform
        if t.arrival_time >= free_platform[1]:
            # Update the train status
            free_platform[1] = t.arrival_time + t.stoppage_time + 1
            # Add the current platform
            # to the pq
            pq.put((-free_platform[1], free_platform))
 
            # Add the platform
            # number to the dictionary
            schedule[t.train_num] = free_platform[0]
        # Otherwise, add a new platform
        # for the current train
        else:
            # Update the priority queue
            pq.put((-free_platform[1], free_platform))
 
            # Get the platform number
            platform_num = pq.qsize() + 1
 
            # Add the platform to
            # the priority queue
            temp = [platform_num, t.arrival_time + t.stoppage_time + 1]
            pq.put((-temp[1], temp))
 
            # Add the platform
            # number to the dictionary
            schedule[t.train_num] = platform_num
 
    # Return the platform on
    # which F train arrived
    return schedule[F]
 
# Driver Code
if __name__ == "__main__":
    trains = []
    trains.append(Train("112567", 2, 1))
    trains.append(Train("112569", 5, 5))
    trains.append(Train("112563", 5, 3))
    trains.append(Train("112560", 3, 7))
    F = "112563"
 
    print(findPlatformOf(trains, len(trains), F))
 
# This code is contriibuted by Aditya Sharma


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
public class Train {
    public string train_num;
    public int arrival_time;
    public int stoppage_time;
 
    public Train(string train_num, int arrival_time, int stoppage_time) {
        this.train_num = train_num;
        this.arrival_time = arrival_time;
        this.stoppage_time = stoppage_time;
    }
}
 
public class PlatformComparator : IComparer<int[]> {
    public int Compare(int[] platform1, int[] platform2) {
        if (platform1[1] == platform2[1]) {
            return platform1[0].CompareTo(platform2[0]);
        }
        return platform1[1].CompareTo(platform2[1]);
    }
}
 
public class Program {
    public static int FindPlatformOf(List<Train> trains, int n, string F) {
        trains.Sort((x, y) => x.arrival_time.CompareTo(y.arrival_time));
 
        var pq = new SortedSet<int[]>(new PlatformComparator());
 
        var temp = new int[] { 1, 0 };
        pq.Add(temp);
 
        var schedule = new Dictionary<string, int>();
 
        foreach (var t in trains) {
            var free_platform = pq.Min;
            pq.Remove(free_platform);
 
            if (t.arrival_time >= free_platform[1]) {
                free_platform[1] = t.arrival_time + t.stoppage_time + 1;
                pq.Add(free_platform);
 
                schedule[t.train_num] = free_platform[0];
            } else {
                pq.Add(free_platform);
 
                int platform_num = pq.Count + 1;
 
                var new_platform = new int[] { platform_num, t.arrival_time + t.stoppage_time + 1 };
                pq.Add(new_platform);
 
                schedule[t.train_num] = platform_num;
            }
        }
 
        return schedule[F];
    }
 
    public static void Main() {
        var trains = new List<Train>() {
            new Train("112567", 2, 1),
            new Train("112569", 5, 5),
            new Train("112563", 5, 3),
            new Train("112560", 3, 7),
        };
 
        string F = "112563";
 
        Console.WriteLine(FindPlatformOf(trains, trains.Count, F));
    }
}


Javascript




// JavaScript code for the approach
 
// Define Train class
class Train {
    // Constructor to initialize the train number, arrival
    // time, and stoppage time
    constructor(train_num, arrival_time, stoppage_time)
    {
        this.train_num = train_num;
        this.arrival_time = arrival_time;
        this.stoppage_time = stoppage_time;
    }
}
 
// Define PlatformComparator class to compare platforms
// based on their availability times
class PlatformComparator {
    // Compare function to compare two platforms
    compare(platform1, platform2)
    {
        // If the availability times of both platforms are
        // same, compare based on platform number
        if (platform1[1] == platform2[1]) {
            return platform1[0] - platform2[0];
        }
        // Otherwise, compare based on availability time
        return platform1[1] - platform2[1];
    }
}
 
// Function to find the platform of a given train based on
// its arrival time and stoppage time
function findPlatformOf(trains, n, F)
{
    // Sort the trains based on their arrival times
    trains.sort((x, y) => x.arrival_time - y.arrival_time);
 
    // Create a set to keep track of available platforms,
    // and add the first platform with number 1 and
    // availability time 0
    let pq = new Set();
    let temp = [ 1, 0 ];
    pq.add(temp);
 
    // Create a dictionary to store the platform number for
    // each train
    let schedule = {};
 
    // Iterate over all the trains
    for (let t of trains) {
        // Find the platform with the earliest availability
        // time
        let free_platform = [... pq][0];
        pq.delete(free_platform);
        // If the train can use the platform immediately,
        // update the availability time of the platform and
        // assign it to the train
        if (t.arrival_time >= free_platform[1]) {
            free_platform[1]
                = t.arrival_time + t.stoppage_time + 1;
            pq.add(free_platform);
 
            schedule[t.train_num] = free_platform[0];
        }
        else {
            // If the train cannot use the platform
            // immediately, add a new platform, update its
            // availability time, and assign it to the train
            pq.add(free_platform);
 
            let platform_num = pq.size + 1;
 
            let new_platform = [
                platform_num,
                t.arrival_time + t.stoppage_time + 1
            ];
            pq.add(new_platform);
 
            schedule[t.train_num] = platform_num;
        }
    }
 
    // Return the platform number of the desired train
    return schedule[F];
}
 
// Create an array of Train objects
let trains = [
    new Train("112567", 2, 1),
    new Train("112569", 5, 5),
    new Train("112563", 5, 3),
    new Train("112560", 3, 7),
];
 
// Define the train number for which the platform needs to
// be found
let F = "112563";
 
// Call the findPlatformOf function with the given trains,
// length of trains array, and desired train number
console.log(findPlatformOf(trains, trains.length, F));


Output: 

3

 

Time Complexity: O(N * log N) 
Auxiliary Space: O(N)



Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads