您的位置:首页 > 编程语言 > C语言/C++

UVA 101 The Blocks Problem

2016-07-22 10:08 489 查看

UVA 101 The Blocks Problem

题目大意:

move a onto b:找到a和b所在列,把a和b数字以上的数字全部放回原位置,然后把a放到b所在的列头

move a over b:找到a所在列,把a数字以上的数字全部放回原位置,然后把a放到b所在的列头

pile a onto b:把b所在列b数字以上的数字全部放回原位置,然后把a和a以上的数字全放到b所在列列头

pile a over b:把a和a以上的数字全放到b所在列列头

解题思路:用栈的思想构造数组来解决

#include <stdio.h>
#include <iostream>
using namespace std;

int s[100][100], oa[100]; // 栈
int num[100], ob;
int top[100]; //头指针

void move(int a, int x) {
for(; s[x][top[x]-1] != a; top[x]--) {
int t = s[x][top[x]-1];
s[t][top[t]] = t;
num[t] = t;
top[t]++;
}
}

void pile(int a, int x) {
for(; s[x][top[x]-1] != a; top[x]--) {
oa[ob] = s[x][top[x]-1];
ob++;
}
}

void over(int b, int y) {
for(; ob >= 0; ob--) {
s[y][top[y]] = oa[ob];
top[y]++;
num[oa[ob]] = y;
}
}

int main() {
int n;
while(scanf("%d", &n) != EOF) {
getchar();
for(int i = 0; i < n; i++) {
s[i][0] = i;
num[i] = i;
top[i] = 1;
}
char com1[100], com2[100];
int a, b;
while(scanf("%s", com1) && com1[0] != 'q') {
scanf("%d%s%d", &a, com2, &b);
int x = num[a], y = num[b];
if(x == y)
continue;
if(com1[0] == 'm') {
ob = 0;
move(a, x);
oa[ob] = a;
top[x]--;
}
else if(com1[0] == 'p') {
ob = 0;
pile(a, x);
oa[ob] = a;
top[x]--;
}
if(com2[1] == 'n') {
move(b, y);
over(b, y);
}
else if(com2[1] == 'v')
over(b, y);
}
for(int i = 0; i < n; i++) {
printf("%d:", i);
for(int j = 0; j < top[i]; j++) {
printf(" %d", s[i][j]);
}
printf("\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva c语言