AT_abc330_c 题解

· · 题解

思路

由于 1 \le D \le 2 \times 10^{12},所以 x 和 y 都不大于 \sqrt{2 \times 10^{12}} \approx 1414214。于是我们可以枚举 x 然后计算 y。

对于每一个算出的 x,最优的 y 显然就是 [\sqrt{D-x^2}] 和 [\sqrt{D-x^2}]+1。这里 [x] 表示不超过实数 x 的最大整数,我们分别计算 |x^2+y^2-D|,然后更新最小值即可。

代码

#include <bits/stdc++.h>
using namespace std;

#define ll long long

int main() {
    ll d, ans = 1e18;
    cin >> d;
    for (ll x = 0; x <= 2e6; x++) {
        ll y = sqrt(d - x * x);
        ans = min(ans, abs(x * x + y * y - d));
        ans = min(ans, abs(x * x + (y + 1) * (y + 1) - d));
    }
    cout << ans;
    return 0;
}