例题8-13 环形跑道 UVa11093

本文讨论了一个简单的模拟问题,即在给定的加油站序列中找出一个起点,使得从该点出发可以完成一圈加油路线,其中每站的加油量大于消耗量。通过模拟从每个加油站开始的情况,如果发现无法完成一圈,则跳过此加油站并从下一个开始尝试,直至找到符合条件的起点或确认无解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.题目描述:点击打开链接

2.解题思路:本题属于简单模拟题,只需要从第一个加油站开始模拟,如果有解,直接输出;否则假设走到加油站p(p>0)时走不下去了,那么可以证明2,3…p都不是解(因为从1到其中任何一个点时油量≥0,情况不比直接从这一点出发坏)因此下一次可以直接从p+1开始模拟。注意每次重新模拟时gas要置零(我在这个地方被坑得好惨==)

3.代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;
typedef long long LL;
const int maxn = 100000 + 10;
int n;
int a[maxn],b[maxn],c[maxn];
int main()
{
	//freopen("test.txt", "r", stdin);
	int T,n;
	scanf("%d", &T);
	int rnd = 0;
	while (T--)
	{
		memset(a, 0, sizeof(a));
		memset(b, 0, sizeof(b));
		memset(c, 0, sizeof(c));
		scanf("%d", &n);
		for (int i = 0; i < n; i++)
			scanf("%d", a + i);
		for (int i = 0; i < n; i++)
		{
			scanf("%d", b + i);
			c[i] = a[i] - b[i];//c是净加油量
		}
		printf("Case %d: ",++rnd);
		LL gas = 0;
		int ok = 0;
		int ans = 0, start;
		while (ans<n)
		{
			start = ans;
			gas = 0;
			int j = start;
			for (;;)
			{
				if (gas + c[j]<0)break;
				gas += c[j];
				j = (j + 1) % n;
				if (j == start){ ok = 1; break; }
			}
			if (j >= ans&&!ok)ans = j + 1;
			else break;
		}
		if (!ok)
			printf("Not possible\n");
		else printf("Possible from station %d\n", ans + 1);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值