用n个宽d,高h,深d的箱子打出高度最高的箱子,下面的箱子的宽度,高度和深度必须大于上面的箱子

这个可写死我了,从晚上六点写到晚上11点,终于写对了,hash_map真的可以,先 放上代码,理论等会当独开一篇文章:

#include<iostream>
#include<vector>
#include<hash_map>
#pragma warning(disable:4786)
using namespace std;

struct Box{
public:
	int width;
	int depth;
	int height;
	
	Box(int w, int d, int h) :width(w), depth(d), height(h){}
	Box() :width(0), depth(0), height(0){}
	bool canBeAbove(Box bottom){
		return (*this).depth > bottom.depth && (*this).height > bottom.height && (*this).width > bottom.width;
	}

};

int stackHeight(vector<Box>& v){
	int sumOfHeight = 0;
	for (int i = 0; i < (int)v.size(); ++i)
		sumOfHeight += v[i].height;
	return sumOfHeight;
}

struct cmp_key
{
	enum
	{   //   parameters   for   hash   table   
		bucket_size = 4,   //   0   <   bucket_size   
		min_buckets = 8  //   min_buckets   =   2   ^^   N,   0   <   N   
	};
	bool operator()(const Box &k1, const Box &k2)const
	{
		if (k1.width != k2.width)
		{
			return k1.width < k2.width;
		}

		if (k1.depth != k2.depth)
		{
			return k1.depth < k2.depth;
		}
		if (k1.height != k2.height)
		{
			return k1.height < k2.height;
		}
		return false;
	}
	
	size_t operator() (const Box& b)const

	{

		return (b.depth + 10 * b.height + 100 * b.width) % 20;

	};
	
};

vector<Box> createStackDP(Box* boxes, Box& bottom, hash_map<Box, vector<Box>, cmp_key>& stack_map, int length){
	hash_map<Box, vector<Box>, cmp_key>::iterator it = stack_map.find(bottom);
	if (it != stack_map.end())
		return stack_map[bottom];
	stack_map.bucket_count();
	int maxHeight = 0;
	vector<Box> max_stack;
	for (int i = 0; i < length; ++i){
		if (boxes[i].canBeAbove(bottom)){
			vector<Box> new_stack = createStackDP(boxes, boxes[i], stack_map,length);
			int new_height = stackHeight(new_stack);
			if (new_height > maxHeight){
				max_stack = new_stack;
				maxHeight = new_height;
			}
		}
	}
	max_stack.push_back(bottom);
	stack_map[bottom] = max_stack;
	return max_stack;
}

void show(Box result){
	cout << result.height << "  ";
}

int layoutBoxes(Box* boxes,int length){
	hash_map<Box, vector<Box>, cmp_key> sm;
	vector<Box> result;
	int old = 0;
	for (int i = 0; i < length; ++i){
		vector<Box> v = createStackDP(boxes, boxes[i], sm, length);
		int new_height = stackHeight(v);
		if (new_height > old){
			old = new_height;
			result = v;
		}
	}
	for (int i = 0; i < (int)result.size(); ++i)
		show(result[i]);
	cout << endl;
	return old;
}

int main(){
	Box boxes[5];
	boxes[0] = Box(1, 1, 1); boxes[1] = Box(3, 3, 3); boxes[2] = Box(2, 2, 2); boxes[3] = Box(5, 5, 5); boxes[4] = Box(4, 4, 4);
	cout << layoutBoxes(boxes, sizeof(boxes) / sizeof(Box)) << endl;

	cin.get();
	return 0;
}


猜你喜欢

转载自blog.csdn.net/YoungStunner/article/details/50583852