搜索+剪枝
参考:https://blog.csdn.net/yopilipala/article/details/74999144
//搜索+剪枝
#include <iostream>
#include <cmath>
using namespace std;int ans = INT_MAX;//初始化
int N, M;//剩余层数m,剩余体积leftV,下层半径preR,下层高度preH,当前表面积总和sumS,
void dfs(int m, int leftV, int preR, int preH, int sumS) {if (!leftV && !m) {//剩余层数m和剩余体积leftV都为0,递归出口if ( sumS < ans)ans = sumS;return;}//剪枝1,体积用不完,if (m * (preH - 1) * (preR - 1) * (preR - 1) < leftV)return;//剪枝2,递归不成功,或者最小表面积已经超出if (m <= 0 || leftV <= 0 || (sumS >= ans && ans))return;for (int i = preR - 1; i >= m; i--) {for (int j = preH - 1; j >= m; j--) {int v = i * i * j;//当前层体积int s = 2 * i * j;//当前层表面积if (m == M)//最底层s += i * i;if (s + sumS >= ans)//剪枝3,最小表面积已经超出continue;dfs(m - 1, leftV - v, i, j, sumS + s);//递归}}
}int main() {cin >> N >> M;//体积,层数dfs(M, N, 100, 1000, 0);//层数,体积,半径,高度,表面积总和,初始值cout << ans << endl;return 0;
}