旅行问题

https://loj.ac/p/10178

John 打算驾驶一辆汽车周游一个环形公路。公路上总共有 n 车站,每站都有若干升汽油(有的站可能油量为零),每升油可以让汽车行驶一千米。John 必须从某个车站出发,一直按顺时针(或逆时针)方向走遍所有的车站,并回到起点。在一开始的时候,汽车内油量为零,John 每到一个车站就把该站所有的油都带上(起点站亦是如此),行驶过程中不能出现没有油的情况。

任务:判断以每个车站为起点能否按条件成功周游一周。

输入格式
第一行是一个整数 n,表示环形公路上的车站数;
接下来 n 行,每行两个整数 p_i,d_i,分别表示表示第 i 号车站的存油量和第 i 号车站到下一站的距离。
输出格式
输出共 n 行,如果从第 i 号车站出发,一直按顺时针(或逆时针)方向行驶,能够成功周游一圈,则在第 i 行输出 TAK,否则输出 NIE。

样例
输入
5
3 1
1 2
5 2
0 1
5 4
输出
TAK
NIE
TAK
NIE
TAK
数据范围与提示
对于全部数据,3<= n <= 10^6,0<= p_i <= 2* 10^9,0< di < 2* 10^9。

计算前缀和 没到一个站点到下个站点能节剩余的汽油(剪掉路程消耗)
使用单调队列 n条路之间(一个循环) 最小的站点的汽油剩余 一定要大于起点前的汽油数量。 最小的站点汽油剩余无问题,那么整个环路的其他站点都没问题
细节就是 环路变成2倍长的数组 顺时针和逆时针 添加的汽油和路径消耗是不一样的(顺时针减少站点右边的路径消耗, 逆时针减去站点左边的路径消耗)

#include <iostream>
#include <vector>
#include <memory.h>
#include <cmath>
#include <deque>
#include <algorithm>
#include <map>


using namespace std;

const int N = 1000010;
int gas[N],dist[N];
long long pre[2*N];
int n;
int ans[N];

/*
5
3 1
1 2
5 2
0 1
5 4

TAK
NIE
TAK
NIE
TAK
*/


int main(){
	scanf("%d",&n);
	for(int i= 1;i<=n;i++) scanf("%d%d",&gas[i],&dist[i]);
	
	for(int i= 1;i<=2*n;i++){
		if(i>n) pre[i] = pre[i-1] +gas[i-n]-dist[i-n];
		else pre[i] = pre[i-1] +gas[i] -dist[i];
		//printf("pre[%d]=%d ",i,pre[i]);
	}
	//printf("\n");
	
	deque<int> q;
	for(int i= 0;i <=2*n;i++){
		while(!q.empty() && i  - q.front() >= n) q.pop_front();
		while(!q.empty() && pre[i] <= pre[q.back()]) q.pop_back();
		q.push_back(i);
		if(i >=n &&  pre[i-n] <= pre[q.front()] ) {
			ans[i-n+1]= 1;
		}
	}
	
	//l r 颠倒gas dist 注意不同的 对应次序
	gas[n+1]=gas[1]; dist[n+1]=dist[1];
	int l =1;int r= n+1;
	while(l<r){
		swap(gas[l],gas[r]);
		swap(dist[l],dist[r-1]);
		l++;r--;
	}
	q.clear(); memset(pre,0,sizeof pre);
	for(int i= 1;i<=2*n;i++){
		if(i>n) pre[i] = pre[i-1] +gas[i-n]-dist[i-n];
		else pre[i] = pre[i-1] +gas[i] -dist[i];
		//printf("gas[%d]=%d, dist[%d]%d, pre[%d]=%d \n",i,gas[i],i,dist[i],i,pre[i]);
	}
	//printf("\n");
	
	for(int i= 0;i <=2*n;i++){
		while(!q.empty() && i  - q.front() >= n) q.pop_front();
		while(!q.empty() && pre[i] <= pre[q.back()]) q.pop_back();
		q.push_back(i);
		if(i >=n &&  pre[i-n] <= pre[q.front()] ) {
			int ii = i-n+1;
			int reali = n+2-ii;
			if(ii==1) reali=ii;
			ans[reali]= 1;
			//printf("revese set reali=%d  true\n",reali);
		}
	}
	
	for(int i =1;i<=n;i++){
		if(1== ans[i]){
			printf("TAK\n");
		}else{
			printf("NIE\n");
		}
	}
	
	return 0;
}

posted on 2026-11-23 16:55  itdef  阅读(2)  评论(0)    收藏  举报

导航