叠积木~~~

#include <iostream>

#include <vector>

#include <string>

#include <sstream>

#include <algorithm>

using namespace std;

// 深度优先搜索函数

bool dfs(const vector<int>& bricks, int currentIndex, int usedLayers, vector<int>& layerLengths, int maxLayers, int targetLength)

{

// 当所有积木都已使用完时,返回 true

if (currentIndex < 0)

{

return true;

}

// 当前层还未堆满,继续往上堆

if (usedLayers < maxLayers)

{

layerLengths[usedLayers] = bricks[currentIndex];

if (dfs(bricks, currentIndex - 1, usedLayers + 1, layerLengths, maxLayers, targetLength))

{

return true;

}

layerLengths[usedLayers] = 0;

}

// 把当前积木加入已有的每一层中,看是否能够满足条件

for (int i = 0; i < usedLayers; i++)

{

// 如果当前层和上一层积木长度相同,则不需要重复计算

if (i > 0 && layerLengths[i] == layerLengths[i - 1])

{

continue;

}

// 如果当前积木可以放入当前层,则把当前积木放入当前层

if (layerLengths[i] + bricks[currentIndex] <= targetLength)

{

layerLengths[i] += bricks[currentIndex];

if (dfs(bricks, currentIndex - 1, usedLayers, layerLengths, maxLayers, targetLength))

{

return true;

}

layerLengths[i] -= bricks[currentIndex];

}

}

return false;

}

int main()

{

// 读取输入

string inputStr;

getline(cin, inputStr);

istringstream iss(inputStr);

vector<int> bricks;

int brick;

while (iss >> brick)

{

bricks.push_back(brick);

}

// 计算所有积木的总长度

int totalLength = 0;

for (int brick : bricks)

{

totalLength += brick;

}

// 对积木长度进行排序

sort(bricks.begin(), bricks.end());

int maxLayers = -1;

// 遍历所有可能的层数

for (int i = 2; i <= totalLength; i++)

{

// 如果所有数字的和除不尽层数,自然肯定不满足条件

if (totalLength % i != 0)

{

continue;

}

// 计算每一层的目标长度

int targetLength = totalLength / i;

// 如果最大的积木长度大于当前层的长度,则无法满足条件

if (bricks.back() > targetLength)

{

continue;

}

// 初始化每层的长度列表

vector<int> layerLengths(i, 0);

// 使用深度优先搜索判断是否可以堆成满足条件的墙

if (dfs(bricks, bricks.size() - 1, 0, layerLengths, i, targetLength))

{

maxLayers = max(maxLayers, i);

}

}

// 输出最大层数

cout << maxLayers << endl;

return 0;

}

相关推荐
fengfuyao98521 小时前
基于Matlab的压缩感知梯度投影重构算法实现方案
算法·matlab·重构
快手技术21 小时前
打破信息茧房!快手搜索多视角正样本增强引擎 CroPS 入选 AAAI 2026 Oral
后端·算法·架构
e***985721 小时前
MATLAB高效算法实战:从基础到进阶优化
开发语言·算法·matlab
CoderCodingNo21 小时前
【GESP】C++五级练习(前缀和练习) luogu-P1387 最大正方形
开发语言·c++·算法
MicroTech20251 天前
MLGO微算法科技通过 Lindbladians 设计线性微分方程的近似最优量子算法——开放量子系统框架下的量子ODE求解新范式
科技·算法·量子计算
知乎的哥廷根数学学派1 天前
基于多尺度特征提取和注意力自适应动态路由胶囊网络的工业轴承故障诊断算法(Pytorch)
开发语言·网络·人工智能·pytorch·python·算法·机器学习
源代码•宸1 天前
Leetcode—85. 最大矩形【困难】
经验分享·算法·leetcode·职场和发展·golang·单调栈
平哥努力学习ing1 天前
《数据结构》-第八章 排序
数据结构·算法·排序算法
CoovallyAIHub1 天前
为AI装上“纠偏”思维链,开源框架Robust-R1显著提升多模态大模型抗退化能力
深度学习·算法·计算机视觉
小棠师姐1 天前
随机森林原理与实战:如何解决过拟合问题?
算法·机器学习·随机森林算法·python实战·过拟合解决