First, the problem description
In the evening of Friday, a gang of colleagues drank a few more drinks at the hard drive bar near the Sigma building. What does the programmer talk about after drinking a few more cups? Nature is an algorithmic problem. One colleague said: "I used to work in a restaurant, and customers often order a lot of pancakes." The size of the cake in the shop is different, I used to arrive at the Customer table, put a stack of cakes in the order of size-small in the top, big under. As I was holding the plate in one hand, I had to use the other hand to catch the top of the cake at once, and turn them upside down, and after a few times, the stacks of pancakes were lined up. I thought later that this was actually an interesting sort of problem: assuming that there are n blocks of different sizes, how many times do we have to double them at least to reach the final size? Can you write a program that outputs the most optimized cake-making process for n-size pancakes?
Second, the problem analysis
First of all see this question, your first feeling must be: Oh, this is a sort of problem. But this problem is different from the general sort, as can be seen from the problem description, each operation is only selected from the first to the Nth pancake, and then the whole upside down (1). The question comes, choose from the first exactly n a pancake, carry upside down (1~n a cake does not have the order), how in each time or several times inversion can make the local order of pancakes? Then go through a series of inversion and then make the whole order. Describe here, have you thought of a solution?
Third, Solution One: First, the top of the pancake and the largest pancake between the pancakes flip, so the biggest pancakes on the top, and then a flip, the biggest pancakes on the bottom
, the biggest pancakes are in their right place. The largest pancake is placed at the lowest part by two flips. Then choose from the top of the pie and the second big pancakes
, repeat the above steps. With every two flips, place the largest pie that is no longer in the correct position on the right position.
So how many times do we need to flip the pancakes to flip them over?
first, after two flips, the largest pancake can be flipped to the bottom. Therefore, it is necessary to flip the top n-1 pancakes in turn two times. So, when we get to the first and second, we need a 2 (n-2) flip. Finally, the first and second will need to be flipped up at most (probably no need at all, already in order).
We have already found a solution, but will there be a better way to achieve the same goal by less flipping?
Consider a situation, such as the above Figure 1, the number 1, 2, 3 of the top three pancakes is actually three adjacent order already row of pancakes. Consider each flip to let the two should be adjacent to the pancake as much as possible to exchange together. In this way, when all the pancakes have been put together, the order is actually finished. (In this sense, every time the biggest pancake to turn the scheme is essentially each time the largest and the second big exchange together, but through the two times, not every time as far as possible to the two should be adjacent to the pancake as far as possible to exchange together)
So what can be done with the fewest flips? Here is not a way to choose a poor lift, all of the situation of each flip, expand to see is a tree, each node has nine sub-nodes (there are nine flip case), if the rollover reached 2n-3 is not yet in the order to truncate this branch. Depending on the current number of flips plus the minimum number of flips (nether values), the lower value can be determined as follows: from the last position, go ahead and find the first pancake number that is different from the final result position (that is, exclude the last few pancakes that are already in place), from that position to the first position, Count the number of adjacent pancakes consecutively, plus 1. ) to determine whether to truncate this branch. We can choose the recursive method of deep traversal of this tree, to get the smallest sequence of those steps.
Five, the Code
Public classcflapjacksorting {Private intM_ncake;//Number of Pancakes Private int[] M_cakearray;//information array of pancakes, that is, the number of inputs to the initial array Private intM_nmaxswap;//maximum number of exchanges Private int[] M_swaparray;//an array that stores Exchange location information Private int[] M_reversecakearray;//at that time flipping pancakes information array Private int[] m_reversecakearrayswap;//an array that stores Exchange location information at that time Private intM_nsearch;//Number of searches Publiccflapjacksorting () {M_ncake= 0; M_nmaxswap= 0; } /** * * @paramPcakearray Information of the pancake entered *@paramthe length of the Ncake array*/ Public voidInitint[] Pcakearray,intNcake) { assert(Pcakearray! =NULL); M_ncake=Ncake; M_cakearray=New int[M_ncake]; assert(M_cakearray! =NULL); //Initialize the pancake array for(inti = 0; i < M_ncake; i++) {M_cakearray[i]=Pcakearray[i]; } M_nmaxswap=Upbound (M_ncake); M_swaparray=New int[M_nmaxswap + 1]; assert(M_swaparray! =NULL); M_reversecakearray=New int[M_ncake]; for(inti = 0; i < M_ncake; i++) {M_reversecakearray[i]=M_cakearray[i]; } M_reversecakearrayswap=New int[M_nmaxswap+1]; } /*** Maximum upper bound: maximum number of times that can be flipped *@paramNumber of ncake pancakes *@return */ Public intUpbound (intNcake) { return2 *Ncake; } /*** Minimum lower bound *@paramPcakearray *@paramNcake *@return */ intLowerbound (int[] Pcakearray,intNcake) { intT, lower = 0; for(inti = 1; i < Ncake; i++) {T= Pcakearray[i]-pcakearray[i-1]; if((t = = 1) | | (t = =-1)) { } Else{Lower++; } } returnLower; } /*** Search Function *@paramStep First*/ Public voidSearchintStep) { intMinestimate;//minimum number of switching estimatesm_nsearch++; Minestimate=lowerbound (M_reversecakearray, M_ncake); if(Step + minestimate >M_nmaxswap)return; //whether the interpretation is well sequenced if(issorted (M_reversecakearray, M_ncake)) {//if ordered, and the number of flips is less than the maximum number of flips. Otherwise, terminate the search if(Step <M_nmaxswap) {M_nmaxswap=step; for(inti = 0; i < M_nmaxswap; i++) {M_swaparray[i]=M_reversecakearrayswap[i]; } } return; } //to Flip for(inti = 1; i < M_ncake; i++) {revert (0, i); M_reversecakearrayswap[step]= i;//record position information for rollover on each rolloverSearch (step + 1); Revert (0, i); } } /*** Determine if the order is orderly *@paramPcakearray *@paramNcake *@return */ Public BooleanIsSorted (int[] Pcakearray,intNcake) { for(inti = 1; i < Ncake; i++) { if(Pcakearray[i] < pcakearray[i-1]) { return false; } } return true; } Public voidRevertintNbegin,intnend) { intT; for(inti = nbegin, j = nend; I < J; i++, j--) {T=M_reversecakearray[i]; M_reversecakearray[i]=M_reversecakearray[j]; M_REVERSECAKEARRAY[J]=T; } } /*** Output Rollover Position information * Number of searches * Number of flips * rollover situation for each step of flipping*/ Public voidoutput () { for(inti = 0; i < M_nmaxswap; i++) {System.out.printf ("%d", M_swaparray[i]); } System.out.printf ("\n| Search times|:%d\n ", M_nsearch); System.out.printf ("Total swap times =%d\n", M_nmaxswap); Perreversearrayoutput (M_cakearray,m_swaparray,m_ncake,m_nmaxswap); } /*** by recording an array of each rollover position, enter an array of each rollover * to display the rollover results for each step *@paramCakearray The first array to sort *@paramSwaparray Record the position of rollover on each rollover *@paramnumber of ncake arrays *@parammaxswap number of flips*/ Public Static voidPerreversearrayoutput (int[] Cakearray,int[] Swaparray,intNcake,intMaxswap) {System.out.printf ("%d\n", Maxswap); intT; for(inti=0;i<maxswap;i++) {System.out.printf ("%d", Swaparray[maxswap]); for(intx = 0,y = Swaparray[i]; x < y; x + +, y--) {T=Cakearray[x]; CAKEARRAY[X]=Cakearray[y]; Cakearray[y]=T; } for(intk=0;k<ncake;k++) {System.out.printf ("%d", Cakearray[k]); } System.out.print ("\ n"); } } Public voidRunint[] Pcakearray,intNcake) {init (pcakearray,ncake); M_nsearch=0; Search (0); }}
VI. Reference Blogs
Jinlei_zhao's Blog (sort of a stack of pancakes)
Huaerge's Blog (sort of a stack of pancakes)
Beauty of programming-pancake sorting problem (JAVA)