您的位置:首页 > 其它

算法竞赛入门经典 例题 9-2 嵌套矩形

2013-06-15 16:30 429 查看
/* 算法竞赛入门经典 例题 9-2 嵌套矩形
* 思路:使用有向无环图 g[i][j]=1表示矩形i可以嵌套在矩形j中
*       d[i]表示从i出发的最长路径长度  状态转移方程: d[i] = max{d[j] + 1,d[i]| g[i][j]=1}
* */
import java.util.Arrays;
import java.util.Scanner;

class Rectangle {
int w;//矩形宽
int h;//矩形高

public Rectangle(int w, int h) {
this.w = w;
this.h = h;
}
}

public class EmbedRectangle {
static final int MAXN = 20;
static Rectangle[] r = new Rectangle[MAXN];
static int[][] g = new int[MAXN][MAXN];
static int[] d = new int[MAXN];
static int n;

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while ((n = scanner.nextInt()) > 0) {
for (int i = 0; i < n; i++) {
int width = scanner.nextInt();
int height = scanner.nextInt();
r[i] = new Rectangle(width, height);
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((r[i].h < r[j].h && r[i].w < r[j].w)
|| (r[i].w < r[j].h && r[i].h < r[j].w)) {
g[i][j] = 1;
} else if ((r[i].h > r[j].h && r[i].w > r[j].w)
|| (r[i].w > r[j].h && r[i].h > r[j].w)) {
g[j][i] = 1;
}
}
}
Arrays.fill(d, 0);//初始化为0
dp(0);
int max = d[0];
int index = 0;//记录最长路径开始位置
for (int i = 1; i < n; i++) {
if (d[i] > max) {
max = d[i];
index = i;
}
}
System.out.println(max);
print_ans(index);
}
}
//记忆搜索程序
private static int dp(int i) {
if (d[i] > 0)
return d[i];
d[i] = 1;
for (int j = 0; j < n; j++) {
if (g[i][j] == 1) {
d[i] = Math.max(d[i], 1 + dp(j));
}
}
return d[i];
}
//打印程序
private static void print_ans(int i) {
System.out.println(r[i].w + " " + r[i].h);
for (int j = 0; j < n; j++) {
if (g[i][j] == 1 && d[i] == d[j] + 1){
print_ans(j);
break;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: