Difficulty difficult 18
There is a car on a single lane n
, and they are driving in the same direction. Give you an n
array of length cars
, where cars[i] = [positioni, speedi]
it means:
positioni
It isi
the distance between the first vehicle and the starting point of the road (unit: meter). Title guaranteepositioni < positioni+1
.speedi
Isi
the initial speed of the first vehicle (unit: m/s).
For simplicity, all cars can be considered as moving points on the number axis. When two cars occupy the same position, we say they meet. Once two cars meet, they will merge into a convoy. The cars in this convoy have the same position and the same speed, and the speed is the speed of the slowest car in the convoy .
Please return an array answer
, which answer[i]
is the first i
time the car next car met (unit: seconds), if the car does not meet with the next car, it answer[i]
is -1
. The accuracy error of the answer must be 10-5
within.
Example 1:
Input: cars = [[1,2],[2,1],[4,3],[7,2]] Output: [1.00000,-1.00000,3.00000,-1.00000] Explanation: After exactly 1 second, The first car will meet the second car and form a 1 m/s fleet. After exactly 3 seconds, the third car will meet the fourth car and form a 2 m/s convoy.
Example 2:
Input: cars = [[3,4],[5,4],[6,3],[9,1]] Output: [2.00000,1.00000,1.50000,-1.00000]
prompt:
1 <= cars.length <= 105
1 <= positioni, speedi <= 106
positioni < positioni+1
By calculating the possible collision time of adjacent cars, put them into the priority queue, and process them according to time. After the collision, the vehicle in front is equivalent to disappearing. Note that to delete the vehicle, it is necessary to maintain an array of all vehicles' survival status to determine whether the vehicle is deleted. At the same time, in order to better find the next vehicle that needs to be found after the collision, a pre array is maintained to store the vehicle in front of each position.
class Solution {
struct Node {
double t;
int l, r;
Node(double tt, int ll, int rr) :t(tt), l(ll), r(rr) {};
bool operator < (const Node& S) const {
return t > S.t;
}
};
public:
vector<double> getCollisionTimes(vector<vector<int>>& cars) {
vector<double>res(cars.size(), -1);
vector<int >pre(cars.size(), 0);
vector<bool>Shan(cars.size(), 0);
priority_queue<Node>room;
for (int i = 1; i < cars.size(); ++i) {
pre[i] = i - 1;
}
for (int i = 1; i < cars.size(); ++i) {
if (cars[i][1] < cars[i - 1][1]) {
double t = ((double)cars[i][0] - cars[i - 1][0]) / (cars[i - 1][1] - cars[i][1]);
//cout << t << endl;
Node save(t, i - 1, i);
room.push(save);
}
}
while (!room.empty()) {
Node N = room.top();
//cout << N.l << ' ' << N.r << ' ' << N.t << endl;
if (!Shan[N.l] && !Shan[N.r])
{
res[N.l] = N.t;
Shan[N.l] = 1;
pre[N.r] = pre[N.l];
if (cars[N.r][1] < cars[pre[N.r]][1]){
double t = ((double)cars[N.r][0] - cars[pre[N.r]][0]) / (cars[pre[N.r]][1] - cars[N.r][1]);
//cout << t << endl;
room.push(Node(t, pre[N.r], N.r));
}
}
room.pop();
}
return res;
}
};