Long time did not write recursion, afraid Rusty again to practice practiced hand.
Test instructions: The N-relay stack shown on the rail, the existing 2n train, gives the train initial number sequence. Train from the far right into the track, and the train can only move from the right to the left, the need to give the train relay operation sequence, so that the train through the N relay stack from the left end of the output to meet the 1~2n arrangement.
Analysis: In fact, this is not the train out of the stack problem, can be divided into the idea of recursion, the first half of order, and then merge to make the whole orderly.
Idea: Specifically, a sequence of unordered (numbered 1~2n), through a relay stack to make 1 ~ 2n-1 in the entire sequence of the front 2n-1+1 ~ 2n at the end of the whole sequence, and then go through the next relay stack, but also further sorting, In this case, the last brokered stack is just a 22 order-disordered problem.
Nothing is as good as examples, such as n=3, when the initial sequence is 2 1 5 8 7 3 6 4
After the stack 1 o'clock, the sequence satisfies the following form: 2 1 3 4 | 6 7 8 5
After the stack 2 o'clock, the sequence satisfies the following form: 2 1 | 3 4 | 6 5 | : U
After the stack 3 o'clock, the sequence satisfies the following form: 1 2 | 3 4 | 5 6 | 7 8
And then the requirements are met.
So what can be done to achieve the above status?
For example, after the stack 1 o'clock, the sequence can be divided into two sequences containing (1~4) and (5~8). Then each to a number, to determine whether the number is greater than 4, if less than or equal to 4, then the train into the stack and then out of the stack, or the train temporarily parked in the stack, and so on all less than equal to 4 of the train out of the stack after the advanced after the nature of the stack, so as to achieve the purpose;
Operation sequence after Stack 1 o'clock: 2 2 1 1 5 8 7 3 3 6 4 4 6 7 8 5
Following the stack of the situation is similar, no longer repeat it.
Attached code:
1#include <iostream>2#include <cstring>3#include <cstdlib>4#include <cstdio>5#include <stack>6 using namespacestd;7 Const intMAXN = the;8 intA[MAXN];9 voidDfsintNum[],intRintk)Ten { One if(k <=1)return ; A ints1[k/2+1]; - ints2[k/2+1]; - intK1 =0, K2 = k/2; the intL = rK; - intMid = (L + r)/2; - -stack<int>si; + intP1, p2; P1 = P2 =0; - for(inti =0; I < K; i++) + { A if(Num[i] <=mid) at { -s1[p1++] =Num[i]; -printf"%d%d", Num[i], num[i]); - } - Else - { inprintf"%d", Num[i]); - Si.push (Num[i]); to } + } - while(!si.empty ()) the { *S2[P2] =si.top (); $printf"%d", s2[p2++]);Panax Notoginseng Si.pop (); - } theDFS (S1, Mid, k/2); +DFS (S2, R, k/2); A return ; the } + - $ intMain () $ { - intN; - while(~SCANF ("%d", &n) &&N) the { - intm =1<<N;Wuyi for(inti =0; I < m; i++) thescanf"%d", &a[i]); - Dfs (A, m, m); Wuprintf"\ n"); - } About return 0; $}
View Code
"Train out of the stack" ZOJ-2603 railroad Sort