一道深搜题,看了这两个博客才懂的。
http://blog.csdn.net/blesslzh0108/article/details/53486168
http://blog.csdn.net/v5zsq/article/details/46575215
#include<iostream> #include<algorithm> #include<cstdio> using namespace std; const int maxn = 0x3f3f3f3f; int minv[21], mins[21]; int ans, mh,n, m; void dfs(int v, int s, int level, int r, int h) { if (level == 0) { if (v == n&&s < ans) ans = s; return; } if (v + minv[level - 1] > n) return; if (s + mins[level - 1] > ans) return; if (2 * (n - v) / r + s >= ans) return; for (int i = r - 1; i >= level; i--) { if (level == m) s = i*i; mh = min(h - 1, (n - v - minv[level - 1]) / (i*i)); for (int j = mh; j >= level; j--) dfs(v + i*i*j, s + 2 * i*j, level - 1, i, j); } } int main() { minv[0] = 0, mins[0] = 0; for (int i = 1; i <= 20; i++) { minv[i] = minv[i - 1] + i*i*i; mins[i] = mins[i - 1] + 2 * i*i; } while (scanf("%d%d",&n,&m)==2) { ans = maxn; dfs(0, 0, m, n + 1, n + 1); if (ans == maxn) ans = 0; printf("%d ", ans); } return 0; }