UVA101木块问题

 

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=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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值