UVa Problem 101 - The Blocks Problem

本文介绍了解决 UVa 在线裁判题目 101 的算法思路及 C++ 实现。针对《The Blocks Problem》这道题,通过模拟操作实现方块堆叠的移动,包括 move 和 pile 操作,并确保每次移动后方块状态正确更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// UVa Problem 101 - The Blocks Problem // Verdict: Accepted // Submission Date: 2011-10-16 // UVa Run Time: 0.020s // // 版权所有(C)2011,邱秋。metaphysis # yeah dot net // // [解题方法] // 模拟题,注意题意的操作中将方块返回原位置是指将方块 i 放到第 i 组方块最上方。 #include <iostream> #include <cstring> #include <set> using namespace std; #define MAXN 25 int blocks[MAXN]; int state[MAXN][MAXN]; int nBlocks; void returning(int x, pair < int, int > xIndex) { for (int i = xIndex.second + 1; i < blocks[xIndex.first]; i++) { int tmp = state[xIndex.first][i]; state[tmp][blocks[tmp]++] = tmp; } blocks[xIndex.first] = xIndex.second + 1; } void moveOver(int a, int b, pair < int, int > aIndex, pair < int, int > bIndex) { returning(a, aIndex); state[bIndex.first][blocks[bIndex.first]++] = a; blocks[aIndex.first] = aIndex.second; } void moveOnto(int a, int b, pair < int, int > aIndex, pair < int, int > bIndex) { returning(b, bIndex); moveOver(a, b, aIndex, bIndex); } void pileOver(int a, int b, pair < int, int > aIndex, pair < int, int > bIndex) { int current = aIndex.second; while (current < blocks[aIndex.first]) state[bIndex.first][blocks[bIndex.first]++] = state[aIndex.first][current++]; blocks[aIndex.first] = aIndex.second; } void pileOnto(int a, int b, pair < int, int > aIndex, pair < int, int > bIndex) { returning(b, bIndex); pileOver(a, b, aIndex, bIndex); } pair < int, int > findIndex(int x) { for (int i = 0; i < nBlocks; i++) for (int j = 0; j < blocks[i]; j++) if (state[i][j] == x) return make_pair(i, j); } void print(void) { for (int i = 0; i < nBlocks; i++) { cout << i << ":"; for (int j = 0; j < blocks[i]; j++) cout << " " << state[i][j]; cout << endl; } } int main(int ac, char *av[]) { int a, b, aIndex, bIndex; string command, action; cin >> nBlocks; for (int i = 0; i < nBlocks; i++) { blocks[i] = 0; state[i][blocks[i]++] = i; } while (cin >> command, strcmp(command.data(), "quit")) { cin >> a >> action >> b; if (a == b) continue; pair < int, int > aIndex = findIndex(a); pair < int, int > bIndex = findIndex(b); if (aIndex.first == bIndex.first) continue; if (strcmp(command.data(), "move") == 0) { if (strcmp(action.data(), "onto") == 0) moveOnto(a, b, aIndex, bIndex); else moveOver(a, b, aIndex, bIndex); } else if (strcmp(action.data(), "onto") == 0) pileOnto(a, b, aIndex, bIndex); else pileOver(a, b, aIndex, bIndex); } print(); return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值