巨人网络2019年春季-长方体模型堆起来的最高高度

问题描述

游戏里有一堆长方体,每个长方体高表示为 h,宽表示为 w,长表示为 l。现在需要把这些模型都堆起来,而且为了使堆起来的模型不倒,上面的模型的宽度和长度必须小于下面的模型。请编写实现算法,求出能堆出的最高高度(这里的高度即堆起来的所有模型的高度之和)
输入描述
第一行输入总长方体模型数量:n,如:2
从第二行开始,每行输入一个长方体模型的高(h)、宽(w)、长(l),以空格分隔开。
如:
3 4 5
6 7 8
输出描述
9
备注
模型总数量 n 小于等于100。

#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>
using namespace std;
typedef struct Bin
{
	Bin(){}
	Bin(int w, int d, int h) :_w(w), _d(d), _h(h){}
	bool canBeAbove(Bin& bottom)
	{
		if (_w < bottom._w && _d < bottom._d)
			return true;
		else
			return false;
	}
	bool operator < (const Bin& bin) const
	{
		if (_w != bin._w)
			return _w < bin._w;
		else
		{
			if (_d != bin._d)
				return _d < bin._d;
			else
				return _h < bin._h;
		}
	}
	int _w;
	int _d;
	int _h;
}Bin;

int getHeight(vector<Bin>& bins)
{
	if (bins.empty())
		return 0;
	int size = bins.size();
	int height = 0;
	for (int i = 0; i < size; i++)
		height += bins.at(i)._h;
	return height;
}

vector<Bin> createBins(vector<Bin>& bins, Bin& bottom, map<Bin, vector<Bin> >& binToList)
{
	vector<Bin> vecBin;
	if (bins.empty())
		return vecBin;
	if (binToList.find(bottom) != binToList.end())
		return binToList.find(bottom)->second;
	int maxHeight = 0;
	vector<Bin> maxBins;
	int n = bins.size();

	for (int i = 0; i < n; i++)
	{
		if (bins.at(i).canBeAbove(bottom))
		{
			vector<Bin> newBins = createBins(bins, bins.at(i), binToList);
			int newHeight = getHeight(newBins);
			if (newHeight > maxHeight)
			{
				maxHeight = newHeight;
				maxBins = newBins;
			}
		}
	}
	maxBins.insert(maxBins.begin(), bottom);
	binToList.insert(pair<Bin, vector<Bin> >(bottom, maxBins));
	return maxBins;
}

void process()
{
	int n;
	vector<Bin> bins;
	map<Bin, vector<Bin> > binToList;
	vector<Bin> results;
	vector<Bin> maxResults;
	int w, d, h;

	while (cin >> n)
	{
		bins.clear();
		binToList.clear();
		for (int i = 0; i < n; i++)
		{
			cin >> h >> w >> d;
			Bin bin(w, d, h);
			bins.push_back(bin);
		}

		int maxHeight = 0;

		for (int i = 0; i < n; i++)
		{
			Bin bottom = bins.at(i);
			results = createBins(bins, bottom, binToList);
			int height = getHeight(results);

			if (height > maxHeight)
			{
				maxHeight = height;
				maxResults = results;
			}
		}
		cout << maxHeight << endl;
	}
}

int main()
{
	process();
	return 0;
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值