叠积木~~~

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

}

相关推荐
LYFlied9 小时前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠9 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
ytttr87310 小时前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab
jianfeng_zhu11 小时前
整数数组匹配
数据结构·c++·算法
smj2302_7968265211 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
LYFlied12 小时前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
唯唯qwe-13 小时前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄13 小时前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
来深圳13 小时前
leetcode 739. 每日温度
java·算法·leetcode
yaoh.wang13 小时前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽