CEOI2003[汉诺塔/hanoi]

首先,肯定最后要移到N所在的那一根杆上,然后参见URAL1054[Hanoi tower]

CODE:

/*

AUTHOR:Su Jiao

DATE:2010-6-10

DESCRIPTION:

@NOI LINUX

CEOI2003 hanoi

*/

#include <stdio.h>

#include <algorithm>

using std::swap;

 

class Application

{

    FILE* in;

    FILE* out;

    static const int STACK=3;

    static const int MAXN=100000;

    static const int MOD=1000000;

    int N;

    int top[STACK];

    int stack[STACK][MAXN];

    public:

    Application(const char* input=0,const char* output=0)

        :in(input?fopen(input,“r”):stdin),

        out(output?fopen(output,“w”):stdout)

    {

        fscanf(in,“%d”,&N);

       for (int i=0;i<STACK;i++)

           fscanf(in,“%d”,top+i);

       for (int i=0;i<STACK;i++)

           for (int j=0;j<top[i];j++)

               fscanf(in,“%d”,stack[i]+j);

    }

    int run()

    {

       int pos[MAXN+1];

       for (int i=0;i<STACK;i++)

           for (int j=0;j<top[i];j++)

               pos[stack[i][j]]=i;

       int f[MAXN+1]={1};

       for (int i=1;i<=N;i++)

           f[i]=f[i-1]*2%MOD;

       int put=pos[N]+1;

       int step=0;

       int A,B,C;

       if (put==1) A=0,B=1,C=2;

       if (put==2) A=1,B=0,C=2;

       if (put==3) A=2,B=0,C=1;

       for (int i=N;i>=1;i–)

           if (pos[i]!=A)

           {

               step=(step+f[i-1])%MOD;

               if (pos[i]==B) swap(A,C);

               if (pos[i]==C) swap(A,B);

           }

           else swap(B,C);

        fprintf(out,“%d\n%d\n”,put,step);

        return 0;

    }

};

 

int main()

{

    Application app(“hanoi.in”,“hanoi.out”);

    return app.run();

}

 

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注