Enter N to get the block numbered 0~n-1, placed in the position of the sequence number 0~n-1. Now the operation of these pieces of wood, the operation is divided into four kinds.
1, move a onto B: The Block A, b on the wood back to their original position, and then put a on B;
2, move a over B: put a block of wood back to their original position, and then send a to the heap containing B;
3, pile a onto B: Put the wood on B back to their original position, and then a together with a block of wood moved to B;
4, pile A over B: move a together with a block of wood to contain B on the heap.
When the input quit, the end of the operation and output 0~n-1 position on the block situation
#include <iostream> #include <algorithm> #include <cstdio> #include <string> #include <
Vector> using namespace std;
const int MAXN = 30;
int n;
Vector<int> PILE[MAXN]; Locate the pile and height of block A and return the caller void Find_block (int A, int& p, int& h) {for (p = 0; p < n;p++) for (h = 0) as a reference. H < pile[p].size ();
h++) {if (pile[p][h] = = a) return; (////////Move all the blocks above the block with H of P heap height) back to in-situ void clear_above (int p, int h) {for (int i = h + 1; i < pile[p].size (); i++) {int m
= Pile[p][i];
Pile[m].push_back (m);
} pile[p].resize (H + 1); (h)//Move the block of P and above to the top of the P2 heap void pile_onto (int p, int h,int p2) {for (int i = h; i < pile[p].size (); i++) pile[p
2].push_back (Pile[p][i]);
Pile[p].resize (h);
void print () {for (int i = 0; i < n; i++) {printf ("%d:", i);
for (int j = 0; J < Pile[i].size (); j + +) printf ("%d", pile[i][j]);
printf ("\ n");
int main () {int A, B;
CIN >> N;
string s1, S2; for (int i = 0; i < n;i++) Pile[i].push_back (i);
while (CIN >> S1 >> a >> s2 >> b) {int PA, Pb, ha, HB;
Find_block (A, PA, ha);
Find_block (b, Pb, HB);
if (PA = pb) continue;//illegal instruction if (S2 = = "onto") Clear_above (Pb, HB);
if (S1 = = "Move") Clear_above (PA, ha);
Pile_onto (PA, ha, pb);
} print ();
return 0; }
Analysis: Extract the common denominator of 4 directives, write functions to reduce the code