题目描述
输入
10 move 9 onto 1 move 8 over 1 move 7 over 1 move 6 over 1 pile 8 over 6 pile 8 over 5 move 2 over 1 move 4 over 9 quit
输出
0: 0 1: 1 9 2 4 2: 3: 3 4: 5: 5 8 7 6 6: 7: 8: 9:
解题思路:这道题做起来思维性较强,也很看中对题目的理解观察能力.
通过对比两条pile语句,以及第1,3语句可以得知,当有over/move时,后面的木块需要归位.
之后会把前面木块以及其上面的木块移至后面木块的上方.
另外注意一下输出:如果该堆没有木块则后面不要有空格,否则木块数据之间用空格作为分隔.
1.首先需要一个函数loc(int num,&pile,&height) 来确定某个木块所在堆数以及木块的高度.
2.然后我们需要一个归位函数goback(int num),给num木块上面的木块进行归位.
3.最后我们需要移动函数move(int num1,int num2) 将木块num1及其上面的木块移至num2所在的堆上.
参考代码
#include<bits/stdc++.h> using namespace std; vector<int> block[30]; int n; void init() {//对木块进行初始化 for (int i = 0; i < n; i++) { block[i].push_back(i); } } void loc(int num, int& pile, int& height) {//对木块进行定位 以引用的形式返回堆和高度. for (int i = 0; i < n; i++) { for (int j = 0; j < block[i].size(); j++) { if (block[i][j] == num) { pile = i; height = j; return; } } } } void goback(int num) {//将num上方的木块进行归位 int pile, height; pile = 0; height = 0; loc(num, pile, height); for (int i = height + 1; i < block[pile].size(); i++) { int temp = block[pile][i]; block[temp].push_back(temp); } block[pile].resize(height + 1);//重新 指定大小. } void move(int num1, int num2) //将num1和其上方的木块放到num2上 { int pile1, height1, pile2, height2; pile1 = 0; height1 = 0; pile2 = 0; height2 = 0; loc(num1, pile1, height1); loc(num2, pile2, height2); for (int i = height1; i < block[pile1].size(); i++) { block[pile2].push_back(block[pile1][i]); } block[pile1].resize(height1); } void print() { for (int i = 0; i < n; i++) { cout << i << ":" << " "; for (int j = 0; j < block[i].size(); j++) { cout << block[i][j] << " "; } cout << endl; } } void solve() { string str, str2, str3, str4; int pile1 = 0, pile2 = 0, height1 = 0, height2 = 0,temp1,temp2; stringstream sm; while (cin >> str && str != "quit") { cin >> str2 >> str3 >> str4; sm.clear(); sm << str2; sm >> temp1; sm.clear(); sm << str4; sm >> temp2; loc(temp1, pile1, height1);//这里不能使用字符串转换函数stoi不然会报错,我也不知道为啥. loc(temp2, pile2, height2); if (pile1 == pile2) { continue; } if (str == "move") { goback(stol(str2)); } if (str3 == "onto") { goback(stol(str4)); } move(stol(str2), stol(str4)); } } int main() { init(); solve(); print(); return 0; }