您的位置:首页 > 其它

UVA101木块问题

2018-01-28 11:21 295 查看


Uva 101 the block problem 木块问题

题目大意:

输入n,得到编号为0~n-1的木块,分别摆放在顺序排列编号为0~n-1的位置。现对这些木块进行操作,操作分为四种。

1、move a onto b:把木块a、b上的木块放回各自的原位,再把a放到b上;

2、move a over b:把a上的木块放回各自的原位,再把a发到含b的堆上;

3、pile a onto b:把b上的木块放回各自的原位,再把a连同a上的木块移到b上;

4、pile a over b:把a连同a上木块移到含b的堆上。

当输入quit时,结束操作并输出0~n-1的位置上的木块情况

Sample 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

Sample Output  

0: 0 

1: 1 9 2 4 

2: 

3: 3 

4: 

5: 5 8 7 6 

6: 

7: 

8: 9:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<vector>
#include<iostream>
using namespace std;

const int maxn=30;
int n;

vector<int>pile[maxn];     /*每个pile[i]是一个vector*/    /*定义了一个以pile为名称的整形数组*/

//找木块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++)  /*move a onto b:把木块a、b上的木块放回各自的原位,再把a放到b上*/
{                              /*move a over b:把a上的木块放回各自的原位,再把a发到含b的堆上*/
if(pile[p][h]==a)          /*pile a onto b:把b上的木块放回各自的原位,再把a连同a上的木块移到b上*/
return ;               /*pile a over b:把a连同a上木块移到含b的堆上*/
}                              /*当输入quit时,结束操作并输出0~n-1的位置上的木块情*/
}
}

//把第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[b].push_back(b);  //把b放回原位
}
pile[p].resize(h+1);     //pile只应保留下标0-h的元素
}

//把第p维高度为h及其上方的木块整体移动到p2维的顶部
void pile_onto(int p,int h,int p2)
{
for(int i=
4000
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++)
{
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);
// print();
while(1)
{
cin>>s1;
if(s1=="quit")
break;
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")
clear_above(pb,hb);
if(s1=="move")
clear_above(pa,ha);
pile_onto(pa,ha,pb);
}
print();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: