uva 254 - Towers of Hanoi

乱搞,java大数过

1、计算2^(n-1)%3,(对应BCA序列)

    n为偶数,2,最后一个落在C上;

    n为奇数,1,最后一个落在B上

2、乱搞,将m减至0即可

貌似有人用二进制过。

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

package pkg254;



/**

 *

 * @author user

 */

import java.io.*;

import java.math.*;

import java.util.*;

import java.text.*;



public class Main {



    /**

     * @param args the command line arguments

     */

    public static BigInteger []POW2 = new BigInteger[101];

    public static BigInteger m;

    public static int A,B,C,n;

    public static void init(){

        POW2[0]=BigInteger.ONE;

        POW2[1]=BigInteger.valueOf(2);

        for(int k=2;k<101;k++)

             POW2[k] = POW2[k-1].multiply(POW2[1]);

        for(int k=0;k<101;k++)

             POW2[k] = POW2[k].subtract(BigInteger.ONE);

    }

    public static void solve(int a,int b,int c,int flag)

    {

        if(flag==0)

        {

             A=a;B=b;C=c;

        }

        else if(flag==1)

        {

             B=a;C=b;A=c;

        }

        else

        {

             C=a;A=b;B=c;

        }

    }

    public static void move(int a,int b,int c,int flag)

    {

        if(m.equals(BigInteger.ZERO))

        {

            solve(a,b,c,flag);

            return ;

        }

        int k;

        for(k=0;k<101;k++)

            if(m.compareTo(POW2[k])<0)

                break;

        k--;

        a-=k;

        m=m.subtract(POW2[k]);

        if(k%2==1)

        {

            b+=k;

            if(!m.equals(BigInteger.ZERO))

            {

                a--;c++;

                m=m.subtract(BigInteger.ONE);

                move(b,c,a,(flag+1)%3);

            }

            else

            solve(a,b,c,flag);

        }

        else

        {

            c+=k;

            if(!m.equals(BigInteger.ZERO))

            {

                a--;b++;

                m=m.subtract(BigInteger.ONE);

                move(c,a,b,(flag+2)%3);

            }

            else

            solve(a,b,c,flag);

        }

    }

    public static void main(String[] args) {

        // TODO code application logic here

        init();

        //Scanner cin = new Scanner (new BufferedInputStream(System.in));

        Scanner cin = new Scanner (new BufferedInputStream(System.in));

       while(cin.hasNext())

        {

            n=cin.nextInt();

            m=cin.nextBigInteger();

            if(n==0)

                break;

            A=n;

            B=C=0;

            move(A,B,C,0);

            System.out.println(A + " " + B + " " + C);

        }

    }

}

  

你可能感兴趣的:(uva)