跳到正文

题解

题解:P13967 [VKOSHP 2024] Two Arrays

Fengwuy1约 4 分钟
原文

这是 2025年11月16日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年11月16日
收录
2025年12月12日
更新
2026年11月19日
篇幅
约 4 分钟
获赞
4
题目
P13967

版本

  1. v2当前
  2. v1

思路:

我们要最少求操作次数。贪心想一下,一定是使修改后的 aia_i 在满足条件下尽量的小。那么是不是就是使我们 aia_i 中的最小值尽量的小。 显然这是满足单调的。所以我们可以二分答案。由于 aia_i 和 bib_i 是同时加 11 的。所以 Δi=ai−bi\Delta_i = a_i-b_i 不变。我们二分一个 midmid。

我们定义:

res:我们假定 aa 数组修改后的数组。

b:修改后的 bb 数组。

mxb:修改后 bb 数组的最大值。

此时就有:

resi←max⁡(mid,ai)max⁡(mid,ai)≤resi≤mid+x1◯mxb−y≤bi≤mxb2◯\begin{aligned} res_i &\gets \max(mid,a_i) \\ \max(mid,a_i)&\le res_i \le mid+x &\textcircled{1} \\ mxb-y &\le b_i \le mx b &\textcircled{2} \end{aligned}

第一个式子是要保证其尽量合法。

我们发现如果我们已经假定了 resres 数组。修改后的 bb 数组就已经确定了。

由于差值不变所以此时有:

bi=resi+Δi3◯mxb=max⁡(resi+Δi)4◯\begin{aligned} b_i&=res_i+\Delta_i&\textcircled{3}\\ mxb&=\max(res_i+\Delta_i)&\textcircled{4} \end{aligned}

将 3◯\textcircled{3} 代入 2◯\textcircled{2} 得:

mxb−y≤resi+Δi≤mxb  ⟹  mxb−y−Δi≤resi≤mxb−Δi\begin{aligned} &mxb-y \le res_i+ \Delta_i \le mx b \\ \implies &mxb-y-\Delta_i \le res_i \le mxb-\Delta_i \end{aligned}

然后我们将:

resi←max⁡(resi,mxb−y−Δi) res_i \gets \max(res_i,mxb-y-\Delta_i)

同样的,也是保证 resres 尽量合法。

怎样判断最终的 resres 合不合法呢? 很简单,只需判断 resi≤mid+x res_i \le mid+x 就行了。

当然,我们可以用 resres 来统计答案。

AC code:
C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5+5;
const int inf = 1e9+7;
int t, n, x, y;
int a[N], b[N];
int delta[N];
int l, r, mid;
int ans;
int res[N];
bool check(int mid) {
	int mxb = -inf;
	for (int i = 1; i <= n; i++) {
		res[i] = max(mid, a[i]);
		mxb = max(mxb, res[i] + delta[i]);
	}
	for (int i = 1; i <= n; i++) {
		res[i] = max(res[i], mxb - y - delta[i] );
		if (res[i] > mid + x) return 0;
	}
	return 1;
}
void solve() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> n >> x >> y;
	l = -inf, r = inf, ans = 0;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
	}
	for (int i = 1; i <= n; i++) {
		cin >> b[i];
		delta[i] = b[i] - a[i];
	}
	while (l + 1 < r) {
		mid = (l + r) >> 1;
		if (check(mid))r = mid;
		else l = mid;
	}
	if (check(r)) {
		for (int i = 1; i <= n; i++)ans += res[i] - a[i];
		cout << ans << "\n";
	} else {
		cout << "-1\n";
	}
}
signed main() {
	cin >> t;
	while (t--)
		solve();
	return 0;
}