算法竞赛入门经典 例题5-2 木块问题(The Blocks Problem,Uva 101)

木块问题(The Blocks Problem,Uva 101)

题目大意:

输入n,得到编号为0n-1的木块,分别摆放在顺序排列编号为0n-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:
一个堆一个一维数组,整体二维数组(不定长数组使用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;
}

输入一共有4种指令,但如果完全独立地处理各指令,代码就会 变得冗长而且易错。更好的方法是提取出指令之间的共同点,编写函数以减少重复代码。

猜你喜欢

转载自www.cnblogs.com/serendipity-my/p/12641327.html
今日推荐