叠积木~~~

#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;

}

相关推荐
关于不上作者榜就原神启动那件事32 分钟前
模拟算法乒乓球
开发语言·c++·算法
Bug退退退12340 分钟前
ArrayList 与 LinkedList 的区别
java·数据结构·算法
88号技师1 小时前
2025年7月一区SCI优化算法-Logistic-Gauss Circle optimizer-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
一个不知名程序员www2 小时前
算法学习入门---二分查找(C++)
c++·算法
2301_807997382 小时前
代码随想录-day26
数据结构·c++·算法·leetcode
闭着眼睛学算法3 小时前
【双机位A卷】华为OD笔试之【排序】双机位A-银行插队【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·c语言·javascript·c++·python·算法·华为od
TL滕3 小时前
从0开始学算法——第一天(认识算法)
数据结构·笔记·学习·算法
小欣加油3 小时前
leetcode 3318 计算子数组的x-sum I
c++·算法·leetcode·职场和发展
love is sour3 小时前
聚类(Clustering)详解:让机器自己发现数据结构
算法·支持向量机·聚类
烟袅3 小时前
LeetCode 142:环形链表 II —— 快慢指针定位环的起点(JavaScript)
前端·javascript·算法