题意翻译

初始时从左到右有n个木块,编号为0~n-1,要求实现下列四种操作:

  • move a onto b: 把a和b上方的木块全部放回初始的位置,然后把a放到b上面
  • move a over b: 把a上方的木块全部放回初始的位置,然后把a放在b所在木块堆的最上方
  • pile a onto b: 把b上方的木块部放回初始的位置,然后把a和a上面所有的木块整体放到b上面
  • pile a over b: 把a和a上面所有的木块整体放在b所在木块堆的最上方

一组数据的结束标志为"quit",如果有非法指令(a和b在同一堆),应当忽略。

输出:所有操作输入完毕后,从左到右,从下到上输出每个位置的木块编号。 感谢U27114 jxdql2001 提供的翻译

题目描述

PDF

UVA101The Blocks Problem (模拟+vector)好题

输入输出格式

输入格式:

 

UVA101The Blocks Problem (模拟+vector)好题

 

输出格式:

 

UVA101The Blocks Problem (模拟+vector)好题

 

输入输出样例

输入样例#1: 复制

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

输出样例#1: 复制

0: 0
1: 1 9 2 4
2:
3: 3
4:
5: 5 8 7 6
6:
7:
8:
9:

分析:

高度不同正好对应vector,且多写写函数,程序规范

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define N 1100
typedef long long ll;
int n;
vector<int>pile[35];
void find_b(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;
    }
}
void clear_b(int p,int h)//木块归位
{
   for(int i=h+1;i<pile[p].size();i++)
   {
       int b=pile[p][i];
       pile[b].push_back(b);
   }
   pile[p].resize(h+1);
}
void onto(int p1,int h,int p2)
{
   for(int i=h;i<pile[p1].size();i++)
   {
       int b=pile[p1][i];
       pile[p2].push_back(b);
   }
   pile[p1].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;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        pile[i].push_back(i);
    string s1,s2;
    while(cin>>s1)
    {
     if(s1=="quit") break;
     cin>>a>>s2>>b;
     int pa,pb,ha,hb;
     find_b(a,pa,ha);
     find_b(b,pb,hb);
     if(pa==pb) continue;
     if(s1=="move") clear_b(pa,ha);
     if(s2=="onto") clear_b(pb,hb);
     onto(pa,ha,pb);
    }
     print();
    return 0;
}

 

相关文章: