UVa 101 The Blocks Problem

UVa 101 The Blocks Problem

#include<cstdio>
#include<cstring>
#include<iostream>
#include<stack>
using namespace std;

const int maxn = 26;
stack<int> q[maxn];
int pos[maxn]; //记录每个方块的位置
int chg[maxn]; //用于临时存放从栈中pop出的数

void clear(int i){ //将目标方块上的方块放回原位
	int p = pos[i];
	int temp;
	while(q[p].top()!=i){
		temp = q[p].top();
		pos[temp] = temp;
		q[p].pop();
		q[temp].push(temp);
	}
}

void pile(int a, int b){ //将a及以上的方块堆放在b所在的方块堆上
	int cnt = 0;
	int temp;
	int p1 = pos[a];
	int p2 = pos[b];
	while(q[p1].top()!=a){
		temp = q[p1].top();
		q[p1].pop();
		pos[temp] = p2;
		chg[cnt++] = temp;
	}
	q[p1].pop();
	pos[a] = p2;
	q[p2].push(a);
	while(--cnt>=0)
		q[p2].push(chg[cnt]);
}

int main(){
	int n,a,b;
	char op1[5],op2[5];
	scanf("%d",&n);
	for(int i = 0;i<n;i++){
		q[i].push(i);
		pos[i] = i;
	}
	while(scanf("%s",op1)&&op1[0]!='q'){
		scanf("%d %s %d",&a,op2,&b);
		if(a==b||pos[a]==pos[b])
			continue;
		if(op1[0]=='m')  //move情况下清空a上的方块
			clear(a);
		if(op2[1]=='n') //onto情况下清空b上的方块
			clear(b);
		pile(a,b);
	}
	int cnt;
	for(int i = 0;i<n;i++){
		printf("%d:",i);
		cnt = 0;
		while(!q[i].empty()){
			chg[cnt++] = q[i].top();
			q[i].pop();
		}
		for(int j = cnt-1;j>=0;j--)
			printf(" %d",chg[j]);
		printf("\n");
	}
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值