题解:CF2253D Hypercarp and Interdimensional Jumps

· · 题解

非常有意思的数学题!

首先也是最重要的转化:我们考虑假设现在是第 i 步,只考虑 x 维度,若我们选择 a+1 的话,它会在 i \dots n 中都会贡献 1,当 i 从 1 \dots n 中,贡献范围恰好是 [1,n],y 维度同理。

所以题目转化为:p 从 [1,n] 中选若干数相加,q 为剩余数相加。

既然这样,我们观察到 p+q=\frac{n(n+1)}{2} 恒成立。

所以贪心来看,我们要求最大的 n 满足 S=\frac{n(n+1)}{2}\le x+y。

再看题目要求的与终点的最短距离:

D=(x-p)^2+(y-q)^2

转化:

D=(x-p)^2+(y-S+p)^2

根据这是一个关于 p 二次函数,对其求导为 0 能求到最小值:

-2(x-p)+2(y-S+p)=0 p_{best}=\frac{x-y+S}{2}

但 p_{best} 可能取不到,左右正整数取最优即可,再把 p 的边界判清楚。

最后我们要处理 x 维度选的数和为 p_{best},y 维度为 S-p_{best}。这个我们只考虑 x 维度,从大到小贪心枚举 i 即可,能减就减掉,根据我们第一步讲的,如果当前你选了 i,相当于你在 n-i+1 这个位置上在选择在 x 维度上 +1。

这样我们就做完了。

#include<bits/stdc++.h>
using namespace std;
namespace CZW {
#define endl "\n"
#define vec std::vector
#define pb push_back
#define eb emplace_back
    using ll = long long;
    using ull = unsigned long long;
    using i128 = __int128;
    using lb = long double;
    void Main() {
        ll x, y;
        cin >> x >> y;
        ll n = sqrtl(2.0 * (x + y));
        while ((n + 1) * (n + 2) / 2 <= x + y) ++n;
        while (n * (n + 1) / 2 > x + y) --n;
        ll s = n * (n + 1) / 2;
        lb pi = (x - y + s) / 2.0;
        ll p1 = floor(pi), p2 = ceil(pi);
        p1 = max(max(0ll, s - y), min(min(s, x), p1));
        p2 = max(max(0ll, s - y), min(min(s, x), p2));
        auto get = [&](ll p)->ll{
            ll q = s - p;
            return (x - p) * (x - p) + (y - q) * (y - q);
        };
        ll best = p1;
        if (get(p2) < get(p1)) best = p2;
        vec<char> ans(n + 1, 'Y');
        ll cur = best;
        for (ll i = n; i >= 1; --i) {
            if (cur >= i) {
                cur -= i;
                ans[n - i + 1] = 'X';
            }
        }
        for (int i = 1; i <= n; ++i) cout << ans[i];
        cout << endl;
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int Test = 1;
    cin >> Test;
    while (Test--) CZW::Main();
    return 0;
}