解题思路:在startFuel条件下能开到最远的加油站limit,在0-limit个加油站中找到油量最大的加油站加油,重复这个操作,如果limit==-1代表能跑到的加油站里所有的油都被加光也没能到达目的地;
class Solution {
public:
set<int>stations_empty;
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations)
{
//dis(stations);
int len = 0;
if (startFuel>=target)
{
return 0;
}
if (stations.empty()&&startFuel<target)
{
return -1;
}
if (startFuel<stations[0][0])
{
return -1;
}
int limit = -1;
while (startFuel<target)
{
limit = max_len(startFuel, stations);//汽车在只消耗初始燃油状态下能开到最远的加油站
if (stations.empty() || limit == -1)
{
break;
}
pair<int, int>_fuel = fuel(stations, limit);
if(stations_empty.find(_fuel.first)==stations_empty.end())
{
stations_empty.insert(_fuel.first);
startFuel+=_fuel.second;
len++;
vector<int> te = { _fuel.first,_fuel.second };
auto pos = find(stations.begin(), stations.end(), te);
stations.erase(pos);
//dis(stations);
}
}
if (startFuel<target||limit==-1)
{
return -1;
}
return len;
}
int max_len(int startFuel, vector<vector<int>>& stations)
{
for (int i = 0; i < stations.size(); i++)
{
if (startFuel<=stations[i][0])
{
if (startFuel == stations[i][0])
{
return i;
}
else
return i - 1;
}
}
return stations.size() - 1;
}
pair<int,int> fuel(vector<vector<int>> stations,int limit)
{
pair<int, int> ans;
for (int i = 0; i <= limit; i++)
{
if (ans.second<stations[i][1])
{
ans.first = stations[i][0];
ans.second = stations[i][1];
}
}
return ans;
}
void dis(vector<vector<int>>n)
{
system("cls");
for (int i = 0; i < n.size(); i++)
{
cout << n[i][0] << " " << n[i][1] << endl;
}
}
};