-
Notifications
You must be signed in to change notification settings - Fork 45
/
boxstack.cpp
84 lines (62 loc) · 1.71 KB
/
boxstack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include<stdio.h>
#include<stdlib.h>
struct Box
{
int h, w, d; // for simplicity of solution, always keep w <= d
};
int min (int x, int y)
{ return (x < y)? x : y; }
int max (int x, int y)
{ return (x > y)? x : y; }
int compare (const void *a, const void * b)
{
return ( (*(Box *)b).d * (*(Box *)b).w ) -
( (*(Box *)a).d * (*(Box *)a).w );
}
int maxStackHeight( Box arr[], int n )
{
Box rot[3*n];
int index = 0;
for (int i = 0; i < n; i++)
{
rot[index].h = arr[i].h;
rot[index].d = max(arr[i].d, arr[i].w);
rot[index].w = min(arr[i].d, arr[i].w);
index++;
rot[index].h = arr[i].w;
rot[index].d = max(arr[i].h, arr[i].d);
rot[index].w = min(arr[i].h, arr[i].d);
index++;
rot[index].h = arr[i].d;
rot[index].d = max(arr[i].h, arr[i].w);
rot[index].w = min(arr[i].h, arr[i].w);
index++;
}
n = 3*n;
qsort (rot, n, sizeof(rot[0]), compare);
int msh[n];
for (int i = 0; i < n; i++ )
msh[i] = rot[i].h;
for (int i = 1; i < n; i++ )
for (int j = 0; j < i; j++ )
if ( rot[i].w < rot[j].w &&
rot[i].d < rot[j].d &&
msh[i] < msh[j] + rot[i].h
)
{
msh[i] = msh[j] + rot[i].h;
}
int max = -1;
for ( int i = 0; i < n; i++ )
if ( max < msh[i] )
max = msh[i];
return max;
}
int main()
{
Box arr[] = { {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32} };
int n = sizeof(arr)/sizeof(arr[0]);
printf("The maximum possible height of stack is %d\n",
maxStackHeight (arr, n) );
return 0;
}