叠积木~~~

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

{

layerLengthsusedLayers = brickscurrentIndex;

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

{

return true;

}

layerLengthsusedLayers = 0;

}

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

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

{

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

if (i > 0 && layerLengthsi == layerLengthsi - 1)

{

continue;

}

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

if (layerLengthsi + brickscurrentIndex <= targetLength)

{

layerLengthsi += brickscurrentIndex;

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

{

return true;

}

layerLengthsi -= brickscurrentIndex;

}

}

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;

}

相关推荐
geats人山人海8 小时前
算法基础第六讲 图论
算法·深度优先·图论
风落青芜10 小时前
排序算法(四):归并排序、计数排序与算法总结
c语言·开发语言·数据结构·算法·排序算法
@陈小鱼11 小时前
基于InceptionTime网络的PPG无创血压估计算法研究
人工智能·python·算法·回归·开源·ppg·血压估计
liulilittle17 小时前
认识麻将 —— 流水及对账
算法·游戏·lua·对账·流水·资金·玩法
郝学胜-神的一滴21 小时前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
青少儿编程课堂2 天前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛
geovindu2 天前
python: KNeighborsClassifier K
开发语言·后端·python·算法
让我们一起加油好吗2 天前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷