加油站--贪心

 

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
	int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
		for (int i = 0; i < gas.size(); i++)
		{
			int sum = 0; bool flag = false;
			if (gas[i] < cost[i])
				continue;
			else
				sum += gas[i] - cost[i];
			for(int j=(i + 1)%gas.size();j%gas.size()!=i;++j,j%=gas.size())
			{
				sum += gas[j];
				if (sum < cost[j])
				{
					flag = true;
					break;
				}
				else
					sum -= cost[j];
			}
			if (!flag)
				return i;
		}
		return -1;
	}
};
int main()
{
	vector<int> gas, cost;
	int a[] = { 1,2,3,4,5 };
	int b[] = { 3,4,5,1,2 };
	for (int i = 0; i < 4; i++)
	{
		gas.push_back(a[i]);
		cost.push_back(b[i]);
	}
	Solution c;
	cout<<c.canCompleteCircuit(gas, cost);
	system("pause");
	return 0;
}
发布了98 篇原创文章 · 获赞 1 · 访问量 4476

猜你喜欢

转载自blog.csdn.net/weixin_40823740/article/details/103710541