您的位置:首页 > 其它

UVa 101 The Blocks Problem

2013-09-10 20:43 375 查看
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");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: