Uva 101 the block problem 木块问题(算法竞赛经典入门)STL vector

题目大意:

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

1,移动到b:把木块a,b上的木块放回各自的原位,再把a放到b上;

2,移动一个b:把一个上的木块放回各自的原位,再把一个发到含b的堆上;

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

4,堆放一个b:把一个连同上木块移到含b的堆上。

当输入退出时,结束操作并输出0〜N-1的位置上的木块情况

样品输入 
10
移动9移动1
移动8移动1
移动7移动1
移动6移动1
桩8超过6
桩8
移动2
移动1 移动4超过9
退出
样本输出 
 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<vector>
#include<iostream>
using namespace std;
const int maxn = 30;
int n;
vector<int> pile[maxn];
//找木块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;
}
//把堆高度为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);
	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 (s1 == "move") clear_above(pa, ha);
		pile_onto(pa, ha, pb);
	}
	print();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43411988/article/details/84864148
今日推荐