跳到正文

题解

题解:AT_agc023_d [AGC023D] Go Home

原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月30日
篇幅
约 2 分钟
获赞
16

版本

  1. v1当前

这题能做出来的,注意力堪比量化调酒师啊……

我至今想不明白,这题是怎么看出来结论的。

先考虑如果车在最两端的两幢楼之间怎么办。

如果最左端的楼人数不比最右端少,那么:

  1. 如果车在最右端的两幢楼之间,除去最右端的楼都会投负方向,显然成立。

  2. 否则,如果先到达最左端的楼,车右边除去最右端的楼都会投最左端的楼;否则不断用右起第二幢代替原来最右边一幢参与决策。

这是有对称性的,所以可以递归做。

代码非常好写。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n, s, a[100005], b[100005];
int work(int L, int R, int pos){
	if (s < a[L])
		return a[R] - s;
	else if (a[R] < s)
		return s - a[L];
	if (b[L] >= b[R]){
		b[L] += b[R];
		return work(L, R - 1, L) + (a[R] - a[L]) * (pos == R);
	}else{
		b[R] += b[L];
		return work(L + 1, R, R) + (a[R] - a[L]) * (pos == L);
	}
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin >> n >> s;
	for (int i = 1; i <= n; i++)
		cin >> a[i] >> b[i];
	if (b[1] < b[n])
		cout << work(1, n, 1);
	else
		cout << work(1, n, n);
	return 0;
}
原文