随笔 - 109, 文章 - 0, 评论 - 3, 阅读 - 51259

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

【力扣】加油站(读题)

Posted on   SaTsuki26681534  阅读(29)  评论(0编辑  收藏  举报

题目描述

image

分析

在思路上并不是很难,是一道贪心题,但是题目中的一些细节理解不好的话稳容易出问题。
这道题在实现上的正确方法应该是:逐个遍历汽车的起点,在每个起点上汽车可能有两个情况:没油或者回到了起点,
如果回到了起点的话,则这个起点是可行的。
而理解错误的地方就在于汽车没油的判定条件。在这道题中,如果汽车在某个位置上的油为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;
}
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示