跳到正文

个人记录

T3题解

MarsPlan2026约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年8月21日
收录
2026年8月21日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 5e5 + 5;
int n, x, y, k, a[N], b[N];
bool check(int h) {
	int ax = max(0LL, h - b[1]), ay = a[1];
	for (int i = 2; i <= n; i++) {
		int nx = min(max(ax - x, max(0LL, h - b[i])), h), ny = min(min(ay + x, a[i]), h);
		if (nx > ny) return false;
		ax = nx, ay = ny;
	}
	return true;
}
void solve() {
	cin >> n >> x;
	for (int i = 1; i <= n; i++) 	cin >> a[i] >> b[i];
	int l = 0, r = 1e18;
	int ans = -1;
	while (l <= r) {
		int mid = (l + r) >> 1;
		if (check(mid)) {
			ans = mid;
			l = mid + 1;
		} else r = mid - 1;
	}
	if (ans == -1) {
		//	cout << "-----\n";
		cout << "-1\n";
		return;
	}
	int tot = 0;
	for (int i = 1; i <= n; i++) 	tot += (a[i] + b[i] - ans);
	cout << tot << '\n';
}
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	int T;
	for (cin >> T; T--;) {
		solve();
	}
	return 0;
}
原文