您的位置:首页 > 其它

UVa 101 - The Blocks Problem

2013-04-30 17:28 351 查看
#include <cstdio>
#include <iostream>
#include <cstring>

struct st_blocks {
int b[30];
unsigned int s;
};
st_blocks st_blk[30]; //30个栈

//显示结果
void print(int n)
{
for(int i=0; i<n; i++) {
printf("%d:", i);
int s = st_blk[i].s;
for(int j=0; j<s; j++) {
printf(" %d", st_blk[i].b[j]);
}
printf("\n");
}
}
//找到b所在的栈
int find_blk(int n, int b)
{
for(int i=0; i<n; i++) {
int s = st_blk[i].s;
for(int j=0; j<s; j++) {
if(st_blk[i].b[j] == b) return i;
}
}
return 0;
}
//对第st_n个栈pop操作
int pop(int st_n) {
int top = --(st_blk[st_n].s);
return st_blk[st_n].b[top];
}
//对第st_n个栈push操作
void push(int st_n, int value)
{
int top = st_blk[st_n].s;
st_blk[st_n].b[top] = value;
++(st_blk[st_n].s);
}
//让a以上的元素回到初始位置,注意:初始位置不会被占。
//为了方便a也被移走了
void mov(int st_a, int a)
{
int b;
while((b = pop(st_a)) != a) {
push(b, b);
}
}
//移动a及以上元素至栈st_b中
void mov_pile(int st_a, int st_b, int a)
{
int top = st_blk[st_a].s;
int i;
for(i=0; st_blk[st_a].b[i]!=a; i++) ;
st_blk[st_a].s = i;
while(i < top) {
push(st_b, st_blk[st_a].b[i]);
i++;
}
}
void solve(int n, int type, int a, int b) {
int st_a = find_blk(n, a);
int st_b = find_blk(n, b);
if(st_a == st_b) return;
if(type & 2) mov(st_a, a);//type = 2,3
if(type & 1) mov(st_b, b);//type = 1,3
switch(type) {
case 0:
mov_pile(st_a, st_b, a);
break;
case 1:
push(st_b, b);
mov_pile(st_a, st_b, a);
break;
case 2:
push(st_b, a);
break;
case 3:
push(st_b, b);
push(st_b, a);
break;
}
}

int main ()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif

int n;
scanf("%d", &n);
//init blocks
for(int i=0; i<n; i++) {
st_blk[i].b[0] = i;
st_blk[i].s = 1;
}
char buff[10];
while(scanf("%s", buff)==1 && strcmp(buff, "quit")!=0 ) {
char type(0); //11:move onto, 10:move over, 01:pile onto, 00:pile over
if(strcmp(buff, "move")==0) type |= 2;
int a, b;
scanf("%d %s %d", &a, buff, &b);
if(strcmp(buff, "onto")==0) type |= 1;
//printf("%d %d %d\n", type, a, b);
if(a == b) continue;
solve(n, type, a, b);
}
print(n);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: