【力扣】加油站(读题)
题目描述
分析
在思路上并不是很难,是一道贪心题,但是题目中的一些细节理解不好的话稳容易出问题。
这道题在实现上的正确方法应该是:逐个遍历汽车的起点,在每个起点上汽车可能有两个情况:没油或者回到了起点,
如果回到了起点的话,则这个起点是可行的。
而理解错误的地方就在于汽车没油的判定条件。在这道题中,如果汽车在某个位置上的油为0,加油站的油为0,消耗的汽油也为0,则汽车是无法发动的,而如果起始的时候没有油但是加油站的油和消耗的汽油刚好相等,则恰好能到达下一个位置。
(。。。其实我还是觉得这题有歧义)
代码
#include<bits/stdc++.h>
using namespace std;
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int cur ;//= 0;
//bool exist = false;;
int result = -1;
for(int i = 0; i < gas.size(); i++){
cur = gas[i] - cost[i];
int j = (i+1)%gas.size();
while(cur > 0 && j != i){
// if(cur + gas[j] - cost[j] < 0){
// //exist = false;
// break;
// }
// if((j + 1)%gas.size() == i){
// exist = true;
// break;
// }
cur += gas[j] - cost[j];
cout<<cur<<endl;
j = (j + 1)%gas.size();
}
// if(exist){
// cur = i;
// break;
// }
if(j == i){
result = j;
break;
}
}
// if(j != i){
// return -1;
// }else{
// return j;
// }
return result;
}
int main(){
int n;
cin>>n;
int tmp;
vector<int> gas;
vector<int> cost;
for(int i = 0; i < n; i++){
cin>>tmp;
gas.push_back(tmp);
}
for(int i = 0; i < n; i++){
cin>>tmp;
cost.push_back(tmp);
}
cout<<canCompleteCircuit(gas, cost);
return 0;
}