JZOJ_7.15C组第三题 汉诺塔

题意

简单的汉诺塔问题,改了一下规则:不能把盘子从1号柱上直接移到3号柱上,也不能把盘子直接从3号柱上移到1号柱上。现在给出盘子的数量,判断它第m个状态时每个盘子都在哪个柱上(初始状态算0)。

思路

这题正解比较神奇。但是我们可以用另一种方法,根据打表,我们能发现,当n为3时,状态从0到27分别为:
1 1 1
2 1 1
3 1 1
3 2 1
2 2 1
1 2 1
1 3 1
2 3 1
3 3 1
3 3 2
2 3 2
1 3 2
1 2 2
2 2 2
3 2 2
3 1 2
2 1 2
1 1 2
1 1 3
2 1 3
3 1 3
3 2 3
2 2 3
1 2 3
我们可以发现,第一个数字是按123321来变化的,第二个数字是按111222333333222111来变化的,以此类推,所以我们可以让m每次%6,输出相应的数字,再让它/3,(考试找到了规律没时间打了)。

代码

#include<cctype>
#include<cstdio>
#include<cstring>
using namespace std;
int t,n,m,k,ans[6]={1,2,3,3,2,1};
void read(int &tot)
{
    tot=0;
    char c=getchar();
    while (!isdigit(c)) c=getchar();
    while (isdigit(c)) tot=(tot<<3)+(tot<<1)+c-48,c=getchar();
}
int main()
{
    read(t);
    while (t--)
    {
        read(n);read(m);
        for (int i=1;i<=n;i++)
        {
            printf("%d",ans[m%6]);
            m/=3;
            if (i!=n) printf(" ");
        }
        printf("\n");
    }
}

猜你喜欢

转载自www.cnblogs.com/HSZGB/p/9315973.html
今日推荐