跳到正文

题解

题解:AT_abc449_d [ABC449D] Make Target 2

JonnynbZLY约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年4月10日
更新
2026年4月10日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

官方题解(原网址) 原题网址

D - Make Target 2 题解 by en_translator


To conveniently handle the expression max⁡(∣x∣,∣y∣)\max(|x|, |y|), we count those with ∣x∣>∣y∣|x| \gt |y| and ∣x∣≤∣y∣|x| \leq |y|, and finally sum them up to find the answer.

Here, we will describe how to count those with ∣x∣>∣y∣|x| \gt |y|. Those with ∣x∣≤∣y∣|x| \leq |y| can be counted likewise.

When ∣x∣>∣y∣|x| \gt |y|, max⁡(∣x∣,∣y∣)=∣x∣\max(|x|, |y|) = |x|. Thus, we may iterate all even numbers xx within L≤x≤RL \leq x \leq R, and for each xx find the number of yy with ∣x∣>∣y∣|x| \gt |y| and D≤y≤UD \leq y \leq U. Since ∣x∣>∣y∣|x| \gt |y| is equivalent to −∣x∣<y<∣x∣-|x| \lt y \lt |x|, for a fixed xx the integers yy to be counted are within max⁡(−∣x∣+1,D)≤y≤min⁡(∣x∣−1,U)\max(-|x| + 1, D) \leq y \leq \min(|x| - 1, U). The number of such yy can be represented as max⁡(0,min⁡(∣x∣−1,U)−max⁡(−∣x∣+1,D)+1)\max(0, \min(|x| - 1, U) - \max(-|x| + 1, D) + 1), which can be computed in O(1)O(1) time for each xx. Hence, those with ∣x∣>∣y∣|x| \gt |y| can be counted in O(X)O(X) time, where X=R−LX = R - L.

Sample code:

C++
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
	int l, r, d, u;
	cin >> l >> r >> d >> u;
	ll ans = 0;

	// |x| > |y|
	for (int x = l; x <= r; x++) {
		if (x % 2 == 0) {
			int D = max(d, -abs(x) + 1);
			int U = min(u, abs(x) - 1);
			int C = U - D + 1;
			ans += max(C, 0);
		}
	}

	// |x| <= |y|
	for (int y = d; y <= u; y++) {
		if (y % 2 == 0) {
			int L = max(l, -abs(y));
			int R = min(r, abs(y));
			int C = R - L + 1;
			ans += max(C, 0);
		}
	}

	cout << ans << '\n';
}
原文