2022 ICPC Southeastern Europe Regional Contest H-Hanoi

传送门

题意:

        汉诺塔问题的变形。第一行输入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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值