HDU1069 Monkey and Banana (DP)
原题地址:http://acm.hdu.edu.cn/showproblem.php?pid=1069
题意
有n个小块,每个块能摆成6种方案,每个小块提供无数个,下一层的长宽都必须严格大于上一层的长与宽。问最高能够叠多高。
思路
将每一块积木进行分解成六种不同的状态,然后对它们按照长宽进行排序,这样就保证了下一层的长宽大于上一层的,然后我们在此基础上选取不同的积木,看选取哪一个积木可以使最后的高度最大。
AC代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
*
* @author wanyu
* @Date: 2018-02-19
* @Time: 20:55
* To change this template use File | Settings | File Templates.
* @desc
*/
public class Main {
private static Block blocks[];
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
int index = 1;
while (in.nextToken() != StreamTokenizer.TT_EOF) {
int n = (int) in.nval;
if (n == 0) break;
blocks = new Block[n * 6];
for (int i = 0; i < n; i++) {
int[] temp = new int[3];
for (int j = 0; j < 3; j++) {
in.nextToken();
temp[j] = (int) in.nval;
}
Decompose(i * 6, temp);
}
Arrays.sort(blocks);
int max = LIS();
System.out.println("Case " + index + ": maximum height = " + max);
index++;
}
}
private static int LIS() {
int[] dp = new int[blocks.length];
for (int i = 0; i < dp.length; i++) {
dp[i] = blocks[i].z;
}
int max = 0;
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < i; j++) {
if (blocks[i].x < blocks[j].x && blocks[i].y < blocks[j].y) {
//长宽严格递减
dp[i] = Math.max(dp[i], dp[j] + blocks[i].z);//选取不同的积木,看可以组合出的最大高度
}
max = Math.max(dp[j], max);
}
}
return max;
}
private static void Decompose(int index, int data[]) {//将一个矩形分解
for (int x = 0; x <= 2; x++) {
for (int y = 0; y <= 2; y++) {
if (y == x) continue;
for (int z = 0; z <= 2; z++) {
if (z == y || z == x) continue;
blocks[index++] = new Block(data[x], data[y], data[z]);
}
}
}
}
}
class Block implements Comparable<Block> {
int x;//长
int y;//宽
int z;//高
public Block(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int compareTo(Block block) {
if (this.x < block.x) {
return 1;
} else if (this.x == block.x) {
if (this.y < block.y) {
return 1;
} else {
return -1;
}
} else {
return -1;
}
}
}