public class Cake {
private int[] mid_cakes;
private int size;
private int[] steps_result;
private int[] steps_swap;
private int min_steps;
private int searchTimes;
public Cake(int[] cakes){
this.mid_cakes = cakes;
size = cakes.length;
steps_result = new int[size * 2];
steps_swap = new int[size * 2];
min_steps = 5*(size+1)/3;
}
public void run() throws Exception {
search(0);
}
public void search(int step) throws Exception{
searchTimes++;
int total = step + lowCounts(mid_cakes);
if(total >= min_steps){
return;
}
if(isSorted(mid_cakes)){
min_steps = step;
for(int i=0; i<size; i++){
steps_result[i] = steps_swap[i];
}
return;
}
for(int i=1; i<size; i++){
reverse(i);
steps_swap[step] = i;
search(step+1);
reverse(i);
}
}
private void reverse(int pos){
for(int i=0,j=pos; i<j; i++,j--){
int temp = mid_cakes[i];
mid_cakes[i] = mid_cakes[j];
mid_cakes[j] = temp;
}
}
public void output(){
System.out.println("The min swap counts is : " + min_steps);
System.out.println("The search times is : " + searchTimes);
System.out.print("The swap steps is : ");
for(int i=0; i<min_steps; i++){
System.out.print(steps_result[i] + " ");
}
System.out.println("\r");
}
private boolean isSorted(int[] cakes){
for(int i=0; i<cakes.length-1; i++){
if(cakes[i] > cakes[i+1]){
return false;
}
}
return true;
}
private int lowCounts(int[] cakes){
int count = 0;
for (int i=0; i<cakes.length-2; i++){
int pace = cakes[i] - cakes[i+1];
if((pace != -1) && (pace != 1)){
count++;
}
}
return count;
}
/**
* @param args
*/
public static void main(String[] args) {
// int[] cakes = {3,2,1,6,5,4,9,8,7,0};
int[] cakes = {4,2,1,3};
Cake cake = new Cake(cakes);
try {
cake.run();
} catch (Exception e) {
e.printStackTrace();
}
cake.output();
}
}
翻饼子问题
最新推荐文章于 2019-02-22 14:50:52 发布