uva 101(线性表)

题解:用栈的数组存木块,然后设置一个数组储存每个木块当前所在的位置,每次移动都要更新,注意不要把位置的储存成了值,另外,如果a和b木块在同一个位置就不需要移动。

例如:

sample input

2

move 0 over 1

move 1 over 0

quit

输出结果是

0:

1: 1 0

#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
const int N = 30;

stack<int> s[N];
int flag[N];
void init (int pl, int bl) {
	while (s[pl].top() != bl) {
		int temp = s[pl].top();
		flag[temp] = temp;
		s[temp].push(temp);
		s[pl].pop();
	}
	return;
}

void change (int bl1, int bl2) {
	stack<int> temp;
	int flag1 = flag[bl1];
	while (s[flag1].top() != bl1) {
		temp.push(s[flag1].top());
		s[flag1].pop();
	}
	temp.push(s[flag1].top());
	s[flag1].pop();
	int flag2 = flag[bl2];
	while (!temp.empty()) {
		s[flag2].push(temp.top());
		flag[temp.top()] = flag2;
		temp.pop();
	}
}

int main() {
	int n, bl1, bl2;
	char keyw1[N], keyw2[N];
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		s[i].push(i);
		flag[i] = i;
	}
	getchar();
	while (1) {
		scanf("%s", keyw1);
		if (keyw1[0] == 'q')
			break;
		scanf("%d%s%d", &bl1, keyw2, &bl2);
		if (keyw1[0] == 'm') {
			if (keyw2[1] == 'n' && flag[bl1] != flag[bl2]) {
				int temp2 = flag[bl2];
				init(temp2, bl2);
				int temp1 = flag[bl1];
				init(temp1, bl1);
				s[temp2].push(bl1);
				s[temp1].pop();
				flag[bl1] = temp2;
			}
			else if (flag[bl1] != flag[bl2]){
				int temp1 = flag[bl1];
				init(temp1, bl1);
				int temp2 = flag[bl2];
				s[temp2].push(bl1);
				s[temp1].pop();
				flag[bl1] = temp2;
			}
		}
		else {
			if (keyw2[1] == 'n' && flag[bl1] != flag[bl2]) {
				int temp2 = flag[bl2];
				init(temp2, bl2);
				change(bl1, bl2);
			}
			else {
				if (flag[bl1] != bl2)
					change(bl1, bl2);
			}
		}
	}
	for (int i = 0; i < n; i++) {
		printf("%d:", i);
		if (!s[i].empty()) {
			stack<int> temp;
			while (!s[i].empty()) {
				temp.push(s[i].top());
				s[i].pop();
			}
			while (!temp.empty()) {
				printf(" %d", temp.top());
				temp.pop();
			}
			printf("\n");
		}
		else
			printf("\n");
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值