加油站问题

题目

在一条环路上有 n 个加油站,其中第 i 个加油站有 gas[i] 升油,假设汽车油箱容量无限,从第 i 个加油站驶往第 (i+1)%n 个加油站需要花费 cost[i] 升油。

请问能否绕环路行驶一周,如果可以则返回出发的加油站编号,如果不能,则返回 -1。
题目数据可以保证最多有一个答案。

数据范围: 1≤n≤104 1≤n≤104 , gas 和 cost 数组中的值满足 1≤val≤105 1≤val≤105

代码

# include <iostream>
# include <vector>
using namespace std;

/**
* @brief 确定出发的加油站位置
* @param num1 加油量
* @param num2 油消耗量
* @return 加油站索引
*/
int gas_station(vector<int>& gas, vector<int>& cost) {
	int sum_total = 0;//用于计算油量总剩余量
	int rest = 0;//当前油剩余量
	int station = 0;//加油站号
	for (int i = 0; i < gas.size(); ++i)
	{
		rest += gas[i] - cost[i];
		sum_total += gas[i] - cost[i];
		//如果当前油剩余量小于0,则换下一个加油站作为出发点,当前加油站和之前加油站都不行
		if (rest < 0) {
			//重置当前油剩余量,加油站换下一个
			rest = 0;
			station = i + 1;
		}
	}
	//如果油量总剩余量小于0,则不能跑一圈
	if (sum_total < 0) {
		return -1;
	}
	else {
		return station+1;
	}
}
int main()
{
	vector<int> gas = { 1, 2, 3, 4, 5 };
	vector<int> cost = { 3,4,5,1,2 };
	int station = gas_station(gas, cost);
	std::cout << station << std::endl;
	system("pause");
	return 0;

}

结果

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值