木块问题Uva101

来源:互联网 发布:plc编程基础教程 编辑:程序博客网 时间:2024/05/22 02:04

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:


紫书上的题,感觉难度倒不是跟大,就是有些麻烦,模拟操作,正常来写也能写出来的,但是为了其他东西,运用了vector来解决。

核心是vector<int>pile[maxn],第一维大小固定(数组,不超过maxn),第二微的大小不固定。即行数固定大小,每行的个数不固定。

以下是代码(紫书中的代码)

#include<iostream>#include<string>#include<vector>using namespace std;const int maxn = 30;int n;vector<int> pile[maxn];void find_block(int a,int &p,int &h)     //找到木块a所在的pile和height {for(p = 0;p<n;p++)for(h=0;h<pile[p].size();h++)if(pile[p][h] == a)return;}void clear_above(int p,int h)    //把第p堆高度为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 pile_onto(int p,int h,int p2)   //把第p堆高度为h及其上方的木块整体移到p2堆的顶部 {for(int i=h;i<pile[p].size();i++)pile[p2].push_back(pile[p][i]);pile[p].resize(h); }   void show() {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; if(s2 == "onto") clear_above(pb,hb); if(s2 == "move") clear_above(pa,ha); pile_onto(pa,ha,pb); } show(); return 0;  }


原创粉丝点击