Highest Stack Box
9.10
You have a stack of n boxs, with widths wi, height hi, and depths di.
The boxes cannot be rotated and can only be stacked on top of one another
if each box in the stack is strictly larger than the box above it in width,
height and depth. Implement a method to build the tallest stack possible,
where the height of a stack is the sum of the heights of each box.
***/
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include <iterator>
using namespace std;
struct box {
int h;
int w;
int d;
};
struct boxstack {
int height;
vector<int> bstack;
};
bool sortbyh(box b1, box b2) {
if(b1.h < b2.h) return true;
else return false;
}
class maxstackbox {
public:
maxstackbox(box *mybox, int size) {
this->mybox = mybox;
this->size = size;
}
~maxstackbox() {
cache.clear();
}
void getmaxstack(int index);
void print();
private:
box *mybox;
int size;
boxstack max;
bool chkvalid(box b1, box b2);
map<int, boxstack> cache;
};
bool maxstackbox::chkvalid(box b1, box b2) {
if(b1.h < b2.h && b1.w < b2.w && b1.d < b2.d) return true;
else return false;
}
void maxstackbox::getmaxstack(int index) {
if(index == size) return;
boxstack cur;
cur.height = mybox[index].h;
cur.bstack.push_back(index);
boxstack curmax;
for(int i = index; i>0; i--) {
if (chkvalid(mybox[i-1], mybox[index]))
{
if (curmax.height < cache[i-1].height)
curmax = cache[i-1];
}
}
if (!curmax.bstack.empty())
{
copy(curmax.bstack.begin(), curmax.bstack.end(),back_inserter(cur.bstack));
cur.height += curmax.height;
}
cache.insert(pair<int, boxstack>(index, cur));
if (cur.height > max.height)
{
max = cur;
}
getmaxstack(index+1);
}
void maxstackbox::print() {
cout<<"max height: "<<max.height<<endl;
for (int i = 0; i< max.bstack.size(); i++)
{
cout<<max.bstack[i]<<", ";
}
}
void main() {
box mybox[5];
int h = 3;
int w = 4;
int d = 2;
for (int i = 0; i < 5; i++)
{
mybox[i].h = h++;
mybox[i].w = w++;
mybox[i].d = d++;
}
mybox[2].w = 3;
sort(mybox, mybox+5, sortbyh);
maxstackbox mb(mybox, 5);
mb.getmaxstack(0);
mb.print();
}
Comments
Post a Comment