编程之美 烙饼排序问题
java实现:
public class Cakes_Test {
private Integer[] m_CakeArray = null;//烙饼信息数组
private Integer m_nCakeCnt;//烙饼个数
private Integer m_nMaxSwap;//最多交换次数,最多为m_nCakeCnt * 2
private Integer[] m_SwapArray = null;//交换结果数组
private Integer[] m_ReverseCakeArray = null;//中间交换结果数组
private Integer[] m_ReverseCakeArraySwap = null;//中间交换结果数组
private Integer m_nSearch;
public Cakes_Test(){
this.m_nCakeCnt = 0;
this.m_nMaxSwap = 0;
}
void run(Integer[] pCakeArray, int nCakeCnt){
init(pCakeArray, nCakeCnt);
m_nSearch = 0;
serch(0);
}
private void init(Integer[] pCakeArray, int nCakeCnt) {
if(pCakeArray == null || nCakeCnt <= 0){
return;
}
m_nCakeCnt = nCakeCnt;
m_CakeArray = pCakeArray;
m_nMaxSwap = upBound(m_nCakeCnt);
m_SwapArray = new Integer[m_nMaxSwap];
m_ReverseCakeArray = m_CakeArray;
m_ReverseCakeArraySwap = new Integer[m_nMaxSwap];
}
private Integer upBound(Integer m_nCakeCnt2) {
return 2 * m_nCakeCnt2;
}
private int lowerBound(Integer[] m_ReverseCakeArray2,
Integer m_nCakeCnt2) {
int result = 0;
for (int i = 1; i < m_nCakeCnt2; i++){
int t = m_ReverseCakeArray2[i] - m_ReverseCakeArray2[i - 1];
if((t == 1) || (t == -1)){
}else{
result++;
}
}
return result;
}
private void serch(int step) {
m_nSearch++;
int nEstimate = lowerBound(m_ReverseCakeArray, m_nCakeCnt);
if(step + nEstimate >= m_nMaxSwap)
return;
if(isSorted(m_ReverseCakeArray, m_nCakeCnt)){
if(step < m_nMaxSwap){
m_nMaxSwap = step;
for(int i = 0; i < m_nMaxSwap; i++){
m_SwapArray[i] = m_ReverseCakeArraySwap[i];
}
}
return;
}
for (int i = 1; i < m_nCakeCnt; i++){
revert(0, i);
m_ReverseCakeArraySwap[step] = i;
serch(step + 1);
revert(0, i);
}
}
private void revert(int nBegin, int nEnd) {
if(nBegin >= nEnd)
return;
for(int i = nBegin, j = nEnd; i < j; i++, j--){
int t = m_ReverseCakeArray[i];
this.m_ReverseCakeArray[i] = m_ReverseCakeArray[j];
this.m_ReverseCakeArray[j] = t;
}
}
private boolean isSorted(Integer[] m_ReverseCakeArray2,
Integer m_nCakeCnt2) {
for(int i = 1; i < m_nCakeCnt2; i++){
if(m_ReverseCakeArray2[i - 1] > m_ReverseCakeArray2[i])
return false;
}
return true;
}
private void output(){
for(int i = 0; i < m_nMaxSwap; i++){
System.out.println(m_SwapArray[i]);
}
}
public static void main(String[] args) throws InterruptedException{
Cakes_Test cake = new Cakes_Test();
Integer[] cakeArray = new Integer[]{3,2,1,6,5,4,9,8,7,0};
cake.run(cakeArray, 10);
cake.output();
}
}