【HDOJ】1069 Monkey and Banana
DP问题,我是按照边排序的,排序既要考虑x也要考虑y,同时在每个面中,长宽也要有序。还有注意状态转移,当前高度并不是之前的最大block叠加的高度,而是可叠加最大高度+当前block高度或者是当前block高度。最后,n^2的复杂度。
#include <stdio.h> #include <stdlib.h> #define MAXTYPE 33 #define MAXNUM 3*MAXTYPE typedef struct { int x, y, z; } rect; rect rects[MAXNUM]; int heights[MAXNUM]; int comp(const void *a, const void *b) { if ( ((rect *)a)->x - ((rect *)b)->x ) return ((rect *)a)->x - ((rect *)b)->x; else return ((rect *)a)->y - ((rect *)b)->y; } void addOth(int i) { int tmp; int x = rects[i].x; int y = rects[i].y; int z = rects[i].z; // 2 tmp = (y<z) ? y:z; rects[i+2].x = tmp; rects[i+2].y = y+z-tmp; rects[i+2].z = x; // 1 tmp = (x<z) ? x:z; rects[i+1].x = tmp; rects[i+1].y = x+z-tmp; rects[i+1].z = y; // 0 tmp = (x<y) ? x:y; rects[i].x = tmp; rects[i].y = x+y-tmp; } int mymax(int a, int b) { return a>b ? a:b; } int main() { int n, total; int i, j, tmp; int case_n = 0; while (scanf("%d", &n)!=EOF && n) { case_n ++; for (i=0; i<3*n; i=i+3) { scanf("%d %d %d", &rects[i].x, &rects[i].y, &rects[i].z); addOth(i); } total = 3*n; qsort(rects, total, sizeof(rect), comp); /* for (i=0; i<total; ++i) printf("%d: %d, %d, %d\n", i, rects[i].x, rects[i].y, rects[i].z); */ heights[0] = rects[0].z; for (i=1; i<total; ++i) { tmp = 0; for (j=i-1; j>=0; --j) { if (rects[j].x<rects[i].x && rects[j].y<rects[i].y && heights[j]>tmp) tmp = heights[j]; } heights[i] = mymax(tmp+rects[i].z, rects[i].z); } tmp = 0; for (i=0; i<total; ++i) { if (heights[i] > tmp) tmp = heights[i]; } printf("Case %d: maximum height = %d\n", case_n, tmp); } return 0; }