#include #include #include #include #include #include #include #include #include using namespace std; class TheBrickTowerMediumDivTwo { public: vector find(vector heights); vector H; vector I; void Permute(int index); int Less_Than(); int min; vector rv; }; #define MAX(a, b) (((a) > (b)) ? (a) : (b)) int TheBrickTowerMediumDivTwo::Less_Than() { int i; for (i = 0; i < I.size(); i++) { if (I[i] < rv[i]) return 1; if (rv[i] < I[i]) return 0; } return 0; /* This will actually never happen */ } void TheBrickTowerMediumDivTwo::Permute(int index) { int i, tmp, d; if (index == I.size()) { d = 0; for (i = 1; i < index; i++) d += MAX(H[I[i]], H[I[i-1]]); if (d < min || (d == min && Less_Than())) { min = d; rv = I; /* This throws out the old rv and makes a copy of I. */ } return; } /* This is the standard recursive permutation -- swap each element in I with the one in index, and call recursively on index+1 */ for (i = index; i < I.size(); i++) { tmp = I[i]; I[i] = I[index]; I[index] = tmp; Permute(index+1); tmp = I[i]; I[i] = I[index]; I[index] = tmp; } } vector TheBrickTowerMediumDivTwo::find(vector heights) { int i; H = heights; min = 48*H.size(); for (i = 0; i < H.size(); i++) I.push_back(i); Permute(0); return rv; }