可以使用二分优化掉一层枚举。经由两层枚举,有 d=k-a^3-b^3 。预处理立方数组 c^3,若在数组里能二分找到 d ,就输出 c^3 对应的 c 。
n=10^3 ,时间复杂度为 O(n^2\log n) 。
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
#define mx 1000
ll k, cube[2 * mx + 10], a, b, c[2 * mx + 10], ci, m, r, cn;
signed main()
{
scanf("%lld", &k);
for (ll i = mx; i >= 1; --i, ++cn)
cube[cn] = -i * i * i, c[cn] = -i;
for (ll i = 1; i <= mx; ++i, ++cn)
cube[cn] = i * i * i, c[cn] = i;
for (a = -mx; a <= mx; ++a)
{
for (b = a; b <= mx; ++b)
{
if (a == 0 || b == 0)
continue;
ll d = k - a * a * a - b * b * b, c3;
ci = lower_bound(cube, cube + cn, d) - cube;
c3 = cube[ci];
d = a * a * a + b * b * b + c3;
if (d == k)
{
printf("%lld %lld %lld", a, b, c[ci]);
return 0;
}
}
}
printf("no solution");
return 0;
}