题解:P12351 「HCOI-R2」哀之距

· · 题解

思路

定义:(a,b) 和 (c,d) 的切比雪夫距离为 \max(|a-c|,|b-d|)。

数据范围:2 \le n \le 2 \times 10^5 ,0 \le x_{i,0} \le x_{i,1} \le 10^{18},0 \le y_{i,0} \le y_{i,1} \le 10^{18}。

因为数据范围太大,我们应当使用 long long。为了确保了无论输入的矩形坐标如何,这些变量都能被正确地更新,我们应将 a 与 c 的初始值设为 LLONG_MAX,把 b 和 d 的初始值设为 LLONG_MIN。

计算最小覆盖矩形的尺寸

更新 a,b,c,d 使得 a 为所有矩形 x_2 的最小值,b 为所有矩形 x_1 的最大值,c为 所有矩形 y_2 的最小值,d 为所有矩形 y_1 的最小值。

AC Code

#include <iostream>
#include <climits>
#include <algorithm>
using namespace std;
#define maxn LONG_LONG_MAX
#define minn LONG_LONG_MIN
#define ll long long
#define upto(i,a,b) for(long long i=1;i<=n;i++)
ll a = maxn, b = minn, c = maxn, d = minn;
ll n;

int main() {
    ios::sync_with_stdio(false);//关流
    cin >> n;
    upto(i, 1, n) {
        ll x1, y1, x2, y2;
        cin >> x1 >> y1 >> x2 >> y2;
        a = min(a, x2);
        b = max(b, x1);
        c = min(c, y2);
        d = max(d, y1);
    }
    ll xx = b - a, yy = d - c;//宽高
    ll ans1 = max(xx, (ll)0); //由于可能存在负数情况,使用max(xx, 0ll)和`max(yy, 0ll)确保宽度和高度非负
    ll ans2 = max(yy, (ll)0); //0ll即(long long)0
    cout << max(ans1, ans2); //宽度和高度中的最大值
    return 0;
}

鸣谢

对于求切比雪夫距离最大值,本篇题解在一定程度上参考了 __CJY__ 求极差的思路,感谢TA。