《Cracking the Coding Interview》——第9章:递归和动态规划——题目10

2014-03-20 04:15

题目:你有n个盒子,用这n个盒子堆成一个塔,要求下面的盒子必须在长宽高上都严格大于上面的。如果你不能旋转盒子变换长宽高,这座塔最高能堆多高?

解法:首先将n个盒子按照长宽高顺序排好序,然后动态规划,我写了个O(n^2)时间复杂度的代码。

代码:

 1 // 9.10 A stack of n boxes is form a tower. where every stack must be strictly larger than the one right above it.

 2 // The boxes cannot be rotated.

 3 #include <algorithm>

 4 #include <cstdio>

 5 #include <vector>

 6 using namespace std;

 7 

 8 struct Box {

 9     // width

10     int w;

11     // height

12     int h;

13     // depth

14     int d;

15     Box(int _w = 0, int _h = 0, int _d = 0): w(_w), h(_h), d(_d) {};

16     

17     bool operator < (const Box &other) {

18         if (w != other.w) {

19             return w < other.w;

20         } else if (h != other.h) {

21             return h < other.h;

22         } else {

23             return d < other.d;

24         }

25     };

26 };

27 

28 int main()

29 {

30     int n, i, j;

31     Box box;

32     vector<Box> v;

33     vector<int> dp;

34     int result;

35     

36     while (scanf("%d", &n) == 1 && n > 0) {

37         v.resize(n);

38         for (i = 0; i < n; ++i) {

39             scanf("%d%d%d", &v[i].w, &v[i].h, &v[i].d);

40         }

41         sort(v.begin(), v.end());

42         dp.resize(n);

43         for (i = 0; i < n; ++i) {

44             dp[i] = v[i].h;

45         }

46         for (i = 0; i < n; ++i) {

47             for (j = 0; j < i; ++j) {

48                 if (v[i].w > v[j].w && v[i].h > v[j].h && v[i].d > v[j].d) {

49                     dp[i] = v[i].h + dp[j] > dp[i] ? v[i].h + dp[j] : dp[i];

50                 }

51             }

52         }

53         result = dp[0];

54         for (i = 1; i < n; ++i) {

55             result = dp[i] > result ? dp[i] : result;

56         }

57         v.clear();

58         dp.clear();

59         printf("%d\n", result);

60     }

61     

62     return 0;

63 }

 

你可能感兴趣的:(interview)