給你n個方塊,其中每個方塊具有它的長寬高(方塊可以任意旋轉放置),方塊數量不限。現在你要堆一個高塔,上面方塊的長和寬必須嚴格小於下面方塊的長和寬。問你能堆起來的最大高度。
先將方塊以長和寬按從小到大排序,然後從小到大以此為底,求出最大高度。dp[i] = max(dp[j])+i.height (j.x<i.x&&j.y<i.y),最後的結果為max(dp)。
import java.util.Arrays; import java.util.Scanner; class Block implements Comparable<Block>{ int x, y, z; Block(int _x, int _y, int _z) { x = _x; y = _y; z = _z; } @Override public int compareTo(Block arg0) { if(x != arg0.x) return x - arg0.x; return y - arg0.y; } } public class hdu1069 { public static void main(String[] args) { // TODO 自動生成的方法存根 Scanner sc = new Scanner(System.in); int cas = 1; while (sc.hasNext()) { int n = sc.nextInt(); if (n==0) { break; } Block[] bk = new Block[6*n]; for (int i = 0; i < n; i++) { int x = sc.nextInt(); int y = sc.nextInt(); int z = sc.nextInt(); bk[6*i] = new Block(x, y, z); bk[6*i+1] = new Block(x, z, y); bk[6*i+2] = new Block(y, x, z); bk[6*i+3] = new Block(y, z, x); bk[6*i+4] = new Block(z, x, y); bk[6*i+5] = new Block(z, y, x); } Arrays.sort(bk); int[] dp = new int[6*n]; //設以誰為底 int ans = 0; for (int i = 0; i < bk.length; i++) { int max = 0; for (int j = 0; j < i; j++) { if ((bk[j].x >= bk[i].x)||(bk[j].y >= bk[i].y)) { continue; } max = Math.max(max, dp[j]); } dp[i] = max+bk[i].z; ans = Math.max(ans, dp[i]); } System.out.println("Case "+cas+": maximum height = "+ans); cas++; } sc.close(); } }