Wood problem (The Blocks Problem, Uva 101)
Subject to the effect:
Input n, numbered 0 to obtain the block n-1, were placed in the order of number 0 position of n-1. These pieces of wood are now operating, the operation is divided into four.
1, move a onto b: the block a, b on the back of each block in situ, and then placed on a b;
2, over a Move b: the block on the back of each of a primary position, and then sent to a stack containing the b;
. 3, b Pile Onto a: b on the block back into their original position, then a block on a moved together with the b;
. 4, Pile a over b: put together on a stack containing a block b is moved.
When the input quit, and outputs the block ending operation at the position where 0 ~ n-1 of
The Sample the Input
10
Move. 9 Onto. 1
Move. 8 over. 1
Move. 7 over. 1
Move. 6 over. 1
Pile. 8 over. 6
Pile. 8 over. 5
Move 2 over. 1
Move. 4 over. 9
quit
the Sample the Output
0: 0
. 1:. 1. 9 2. 4
2:
. 3 : 3
4:
5: 7. 6 8 5
6:
7:
8:
9:
a stack of a one-dimensional array, the entire two-dimensional array ( variable length arrays used to complete the STL vector )
//数据结构的核心是vector<int>pile[maxn],所有操作都是围绕它进行的。vector就像一个 二维数组,只是第一维的大小是固定的(不超过maxn),但第二维的大小不固定。
#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 25;
int n;
vector<int> pile[maxn]; //每个pile[i]是一个vector
//返回木块a所在的pile和height
void find_block(int a,int &p,int &h)
{
for(p=0;p<n;p++)
{
for(h=0;h<pile[p].size();h++)
{
if(pile[p][h]==a) return ;
}
}
}
//将第p堆高度为h的木块上方的所有木块移回原位
void clear_above(int p,int h)
{
for(int i=h+1;i<pile[p].size();i++)
{
int b=pile[p][i]; //pile[p] 是vector ,vector [i]
//放回原位
pile[b].push_back(b); //就是放回到原来的那一堆里
}
pile[p].resize(h+1);
}
//把第p堆高度为h及其上方的木块整体移动到p2 堆的顶部
void pile_onto(int p,int h,int p2)
{
for(int i=h;i<pile[p].size();i++)
{
pile[p2].push_back(pile[p][i]);
}
pile[p].resize(h);
}
//打印
void print()
{
for(int i=0;i<n;i++)
{
cout<<i<<":";
for(int j=0;j<pile[i].size();j++)
{
cout<<" "<<pile[i][j];
}
}
cout<<endl;
}
int main()
{
string s1,s2; //每个指令都得出现要移动的堆和将要移动到的堆,所以需要两个字符串
int a,b;
cin>>n;
for(int i=0;i<n;i++)
pile[i].push_back(i);
while(cin>>s1&&s1!="quit"&&cin>>a>>s2>>b)
{
int pa,pb,ha,hb;
find_block(a,pa,ha);
find_block(b,pb,hb);
if(pa==pb) continue; //非法指令
if(s2=="onto") //onto: b上的木块放回原位
clear_above(pb,hb);
if(s1=="move") //move: a上的木块放回原位
clear_above(pa,ha);
pile_onto(pa,ha,pb);
}
print();
return 0;
}
There are four kinds of input instructions, but if completely independent processing of each instruction, the code becomes tedious and error-prone. A better approach is common among the extracted command, write the function to reduce duplication of code.