非常麻烦的剪枝条件!
思路
表面积S = 2πr^ h; 体积V = πr^2 h;根据题意可以在计算时约去π。由于蛋糕的高度和半径都是需要逐层递减的,所以最大高度和最大的半径都一定是小于n的,我们通过dfs暴力搜索,枚举每一层可能的高度h和半径r,直到找到层数和体积都符合题意,而且使得表面积最小的答案。
有几个要进行剪枝的地方:
1. 已经用的表面积比当前最优答案大或者是此时体积体积超出题目要求的范围
2.当前的表面积 + 用去侧面积 >= 当前答案值(关键剪枝)
然后就可以解出结果啦!直接放全部代码,看注解即可。
#include <iostream>
#include<cmath>
#include <ctime>
#include<cstdio>
using namespace std;
const int N = 1e4 + 50;
const int MAXN = 1e7;
int v[N], s[N];
int n, m, ans = MAXN;
void dfs(int now, int r, int h, int ss, int vv)
{
if(now == 0)
{
if(vv == n)
{
ans = min(ans, ss);
}
return;
}
if(ss >= ans || vv > n)
{
return;
}
if(2 * (n - vv - v[now - 1]) / r + ss >= ans)
{
return;
}
for(int i = r - 1; i >= now; i--)
{
if(now == m)
{
ss = pow(i, 2);
}
int maxh = h;
maxh = min(h - 1 ,(n - v[now - 1] - vv) / (i * i));
for(int j = maxh; j >= now; j--)
{
dfs((now - 1), i, j, (ss + 2 * i * j), (vv + pow(i, 2) * j));
}
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; i++)
{
s[i] = s[i - 1] + 2 * pow(i, 2);
v[i] = v[i - 1] + pow(i, 3);
}
dfs(m, n, n, 0, 0);
if(ans == MAXN)
{
cout << 0 << endl;
}
else
{
cout << ans << endl;
}
}
这题真的好麻烦啊!!!!