Car Fleet in C++

C++Server Side ProgrammingProgramming

Suppose there are N cars that are going to the same destination along a one lane road. The destination is ‘target’ miles away. Now each car i has a constant speed value speed[i] (in miles per hour), and initial position is position[i] miles towards the target along the road.

A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed. Here the distance between these two cars is ignored - they are assumed to have the same position. A car fleet is some non-empty set of cars driving at the same position and same speed. If one car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. So we have to find how many car fleets will arrive at the destination.

So if the target is 12, if position is [10,8,0,5,3] and speed is [2,4,1,1,3] then the output will be 3. This is because the cars starting at 10 and 8 become a fleet, meeting each other at 12. Now the car starting at 0 doesn't catch up to any other car, so it is a fleet by itself. Again the cars starting at 5 and 3 become a fleet, meeting each other at 6.

To solve this, we will follow these steps −

  • Make an array v, n := size of position array p
  • for i in range 0 to n – 1
    • insert (p[i], s[i]) into v
  • ret := n
  • sort v array
  • define a stack st
  • for i in range 0 to n – 1
    • temp := (t – first element of v[i]) / second element of v[i]
    • while st is not empty and stack top <= temp
      • decrease ret by 1
      • delete top element from st
    • insert temp into st
  • return ret.

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int carFleet(int t, vector<int>& p, vector<int>& s) {
      vector < pair <double, double> > v;
      int n = p.size();
      for(int i = 0; i < n; i++){
         v.push_back({p[i], s[i]});
      }
      int ret = n;
      sort(v.begin(), v.end());
      stack <double> st;
      for(int i = 0; i < n; i++){
         double temp = (t - v[i].first) / v[i].second;
         while(!st.empty() && st.top() <= temp){
            ret--;
            st.pop();
         }
         st.push(temp);
      }
      return ret;
   }
};
main(){
   vector<int> v1 = {10, 8, 0, 5, 3};
   vector<int> v2 = {2,4,1,1,3};
   Solution ob;
   cout << (ob.carFleet(12, v1, v2));
}

Input

12
[10,8,0,5,3]
[2,4,1,1,3]

Output

3
raja
Published on 05-May-2020 13:57:23
Advertisements