# 第 230 场周赛记录（283 / 3727）

class Solution {
static class Car {
double collisionTime;
int index;
int last;
int next;
int pos;
int speed;

public Car(double collisionTime, int index, int last, int next, int pos, int speed) {
this.collisionTime = collisionTime;
this.index = index;
this.last = last;
this.next = next;
this.pos = pos;
this.speed = speed;
}

@Override
public String toString() {
return "Car{" +
"collisionTime=" + collisionTime +
", index=" + index +
", last=" + last +
", next=" + next +
", pos=" + pos +
", speed=" + speed +
'}';
}
}

public double[] getCollisionTimes(int[][] cars) {
PriorityQueue<Car> queue = new PriorityQueue<>(new Comparator<Car>() {
@Override
public int compare(Car car, Car t1) {
return car.collisionTime > t1.collisionTime ? 1 : -1;
}
});

int minSpeed = Integer.MAX_VALUE;
Car[] carList = new Car[cars.length];
for (int i = 0; i < cars.length;i++) {
int pos = cars[i][0];
int speed = cars[i][1];
minSpeed = Math.min(speed, minSpeed);
Car car;
if (i + 1 >= cars.length) {
car = new Car(Double.MAX_VALUE,
i, i-1, i+1, pos, speed);
} else {
int nextPos = cars[i + 1][0];
int nextSpeed = cars[i + 1][1];
car = new Car(getCollsionTime(speed, nextSpeed, nextPos - pos),
i, i - 1, i + 1, pos, speed);
}
queue.offer(car);
carList[i] = car;
}
//System.out.println(Arrays.toString(carList));

double[] result = new double[cars.length];
while (!queue.isEmpty()) {
Car car = queue.poll();
if (result[car.index] != 0 || carList[car.index] != car) {
continue;
}
if (car.speed == minSpeed) {
result[car.index] = -1.0;
continue;
}
result[car.index] = car.collisionTime;

// 存在下一辆车
if (car.next < cars.length) {
Car nextCar = carList[car.next];
// 下一辆车的上一个节点要变化
Car newNextCar = new Car(nextCar.collisionTime, nextCar.index, car.last, nextCar.next, nextCar.pos, nextCar.speed);
queue.offer(newNextCar);
carList[newNextCar.index] = newNextCar;
} else if (car.next == cars.length) {
// 下游没车了。而自己又是自持colletion最大的？
result[car.index] = -1.0;
}

// 存在上一辆车
if (car.last >= 0) {
Car lastCar = carList[car.last];
// 上一俩车的下游车变成了nextCar

double collsionTime;
if (car.next < cars.length) {
Car nextCar = carList[car.next];
collsionTime = getCollsionTime(lastCar.speed, nextCar.speed, nextCar.pos - lastCar.pos);
} else {
collsionTime = Double.MAX_VALUE;
}

Car newLastCar = new Car(collsionTime,
lastCar.index, lastCar.last, car.next, lastCar.pos, lastCar.speed
);
queue.offer(newLastCar);
carList[newLastCar.index] = newLastCar;
}
}

for (int i = 0; i < result.length;i++) {
if (new Double(result[i]).equals(Double.MAX_VALUE)) {
result[i] = new Double(-1);
}
}
return result;
}

public double getCollsionTime(int vLeft, int vRight, int d) {
if (vLeft > vRight) {
return (double)(d)/(vLeft - vRight);
} else {
return Double.MAX_VALUE;
}
}
}

07-11 157
09-06 41
01-31 39
©️2020 CSDN 皮肤主题: 鲸 设计师:meimeiellie