第一次写的时候空间溢出了
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
node cur(0,startFuel,0,-1) , next;
priority_queue<node> q;
q.push(cur);
while(!q.empty()){
cur = q.top();
q.pop();
if(cur.pos+cur.fuel >= target)
return cur.cnt;
int idx; //当前的油量,最大能到达哪个加油站
for(int i=cur.idx+1;i<stations.size();i++){
int d = stations[i][0];
int dist = stations[i][0]-cur.pos;
if(stations[i][0]-cur.pos <= cur.fuel){
next.cnt = cur.cnt+1;
next.fuel = cur.fuel+stations[i][1]-dist;
next.pos = stations[i][0];
next.idx = i;
q.push(next);
}
else
break;
}
}
return -1;
}
优化后的算法时间复杂度下降较大,是线性关系,考虑了贪心的思想,能不加油的时候则不加油,只有无法到达的时候才进行加油,并且是直接线性向后的,避免了特别多的重复状态。
原来的算法是,只要有加油站,就考虑加油和不加油两个状态,其实要贪心的进行考虑:
1.能不加油,则不加油 2.加油的时候,因为代价是次数,则既然加一次,则优先考虑油量多的进行加油
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
vector<int> vec;
vec.push_back(target);
vec.push_back(0); //目标节点的距离为target,加油量为0,将目标节点也看为一个加油站
stations.push_back(vec);
int n = stations.size(); //加油站的个数
int res = 0; //最少的加油次数
int fuel = startFuel; //当前具有的油量
int last = 0; //当前的位置,now是要达的位置
priority_queue<int> q;
for(int i=0;i<n;i++){ //考虑每一个加油站
int now = stations[i][0]; //当前要到达到达位置,last是当前的位置
fuel -= now-last;
while(fuel<0){ //若该位置不可到达,进行加油,并且加油次数不止一次
if(q.empty()) return -1;
fuel += q.top();
q.pop();
res++; //加油次数+1
}
q.push(stations[i][1]);
//记录的是路过的加油站,默认是不加油,只有到达某个位置油量不够时,才考虑加油,这样减少了很多状态,而且优先考虑的是油量多的加油站
last = now;
}
return res;
}