题意:
汉诺塔问题的变形。第一行输入n,第二行输入n个数,是第一根柱子上的数字从底向上的顺序。第一根柱子上的排序,没有要求,但是另外两根柱子必须是大的在下面,小的在上面。然后让你通过一系列操作后,把所有的数字都移动到第三根柱子上(不需要是最小操作次数)。
思路:
因为对操作次数没有要求,所以写的挺暴力。开了三个栈,分别代表三根柱子上的数字排序。然后一个队列用来储存操作顺序。
我们先将第一个柱子上的数字尽可能往第三根柱子上放,然后放到不能再放了。再将第一个柱子上的数字尽可能放到第二根柱子上,放到不能再放了。然后再将第二个柱子和第三个柱子上的所有数字从小到大往第一根柱子上放。一直循环这个操作,直到第一根柱子在往第三根柱子上放数字时能全部放上去,跳出循环。输出答案。
可能文字叙述看不太懂,建议先看一遍代码,代码很容易理解,然后手动模拟一下,就浅显易见了。
代码:
#include <bits/stdc++.h>
using namespace std;
#define int long long
typedef pair<int, int> PII;
int n, m, k;
int T;
stack<int> st[5];
queue<PII> q;
signed main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 0; i < n; i++) //输入第一个柱子上的数字
{
int x;
cin >> x;
st[1].push(x);
}
while (1)
{
//一定要先放到第三个柱子上,因为最终结果是数字全在第三个柱子上
while (st[1].size() && (!st[3].size() || st[3].top() > st[1].top()))
{
st[3].push(st[1].top());
st[1].pop();
q.push({1, 3});
}
if (st[3].size() == n) //可以一次性把第一个柱子上的全部数字都放到第三个柱子上,break
break;
//第三个柱子不能继续放了,尽可能的放到第二个柱子上
while (st[1].size() && (!st[2].size() || st[2].top() > st[1].top()))
{
st[2].push(st[1].top());
st[1].pop();
q.push({1, 2});
}
//下面的三个while循环,是把第二根,第三根上的所有数字按照从小到大的顺序放回第一个柱子上
while(st[2].size()&&st[3].size())
{
if(st[2].top()<st[3].top())
{
st[1].push(st[2].top());
st[2].pop();
q.push({2, 1});
}
else
{
st[1].push(st[3].top());
st[3].pop();
q.push({3, 1});
}
}
while(st[2].size())
{
st[1].push(st[2].top());
st[2].pop();
q.push({2, 1});
}
while(st[3].size())
{
st[1].push(st[3].top());
st[3].pop();
q.push({3, 1});
}
}
cout << q.size() << "\n";
while(q.size())
{
PII t = q.front();
int t1 = t.first, t2 = t.second;
cout << t1 << " " << t2 << "\n";
q.pop();
}
return 0;
}