1. 程式人生 > >LC 871. Minimum Number of Refueling Stops

LC 871. Minimum Number of Refueling Stops

posit 是什麽 least ini 什麽 sid cannot for when

A car travels from a starting position to a destination which is target miles east of the starting position.

Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0]miles east of the starting position, and has station[i][1] liters of gas.

The car starts with an infinite tank of gas, which initially has startFuel

liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.

When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.

What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1

.

Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

經典的小車加油問題。

【一定要註意看題,每個變量是什麽意思。前幾次都把stations[i][0]看成相鄰兩個加油站的距離了。。。】

利用優先隊列。因為要求最小的加油次數,到了一個加油站不加油,但進入優先隊列,不能到達終點或者下一個加油站的時候再取最大的。

 1 class Solution {
 2 public:
 3     int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
 4         priority_queue<int> pq;
 5         int driven = 0;
 6         int idx = 0;
 7         int ret = 0;
 8         while (startFuel < target) {
 9             if (idx >= stations.size()) {
10                 if(pq.empty()) return -1;
11                 while (!pq.empty() && startFuel < target) {
12                     startFuel += pq.top(); pq.pop();
13                     ret++;
14                 }
15                 if (startFuel >= target) return ret;
16                 else return -1;
17             }
18             if (startFuel >= stations[idx][0]) {
19                 pq.push(stations[idx][1]);
20             }
21             else {
22                 if (pq.empty()) return -1;
23                 while (!pq.empty() && startFuel < stations[idx][0]) {
24                     startFuel += pq.top(); pq.pop();
25                     ret++;
26                     if (startFuel >= target) return ret;
27                 }
28                 if(startFuel < stations[idx][0]) return -1; 
29                 pq.push(stations[idx][1]);
30             }
31             idx++;
32         }
33         return ret;
34     }
35 };

另一個種解法:

 1     int minRefuelStops(int target, int cur, vector<vector<int>> s) {
 2         int i = 0, res;
 3         priority_queue<int>pq;
 4         for (res = 0; cur < target; res++) {
 5             while (i < s.size() && s[i][0] <= cur)
 6                 pq.push(s[i++][1]);
 7             if (pq.empty()) return -1;
 8             cur += pq.top(), pq.pop();
 9         }
10         return res;
11     }

LC 871. Minimum Number of Refueling Stops