动态规划实现,用二维数组存储各个面朝上的情况
package Ch9;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int turn=1;
while (true) {
int number = Integer.parseInt(in.nextLine());
if (number == 0)
break;
Cube[][] cubes = new Cube[6][number];
for (int i=0; i<number; i++) {
String[] faces = in.nextLine().split(" ");
cubes[0][i] = new Cube(faces[0], faces[1], "front", i+1);
cubes[1][i] = new Cube(faces[1], faces[0], "back", i+1);
cubes[2][i] = new Cube(faces[2], faces[3], "left", i+1);
cubes[3][i] = new Cube(faces[3], faces[2], "right", i+1);
cubes[4][i] = new Cube(faces[4], faces[5], "top", i+1);
cubes[5][i] = new Cube(faces[5], faces[4], "bottom", i+1);
}
for (int i=1; i<number; i++) {
for (int j=0; j<i; j++) {
for (int m=0; m<6; m++)
for (int n=0; n<6; n++) {
if (cubes[m][j].bottom==cubes[n][i].top && cubes[n][i].height<cubes[m][j].height+1) {
cubes[n][i].height = cubes[m][j].height+1;
cubes[n][i].previous = cubes[m][j];
}
}
}
}
int maxi=0, maxj=0;
for (int i=0; i<number; i++) {
for (int j=0; j<6; j++) {
if (cubes[j][i].height > cubes[maxj][maxi].height) {
maxi = i;
maxj = j;
}
}
}
if (turn>1)
System.out.println("");
System.out.println("Case #" + (turn++));
Cube target = cubes[maxj][maxi];
System.out.println(target.height);
List<Cube> path = new ArrayList<Cube>();
while (target != null) {
path.add(target);
target = target.previous;
}
for (int i=path.size()-1; i>=0; i--)
System.out.println(path.get(i).turn + " " + path.get(i).topName);
}
}
}
class Cube {
public int top;
public int bottom;
public String topName;
public int height;
public Cube previous;
public int turn;
public Cube(String top, String bottom, String topName, int turn) {
this.top = Integer.parseInt(top);
this.bottom = Integer.parseInt(bottom);
this.topName = topName;
this.height = 1;
this.previous = null;
this.turn = turn;
}
}