(UVA) Hanoi Tower Troubles Again - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1217

Every ball is tested in all the N pegs until it finds a peg that is empty or until the sum of the current ball and the ball in the top of the peg is a square number.


import java.io.*;
import java.util.*;

class Main {
    public static int numPegs;
    public static HashMap<Integer, ArrayList<Integer>> pegStruct;
    public static int maxBall;
    public static boolean gotAnswer;
   
    public static void rec(int numBall) {
        if (numBall > maxBall) {
            maxBall = numBall;
        }
       
        for (int i = 0; i < numPegs && !gotAnswer; i++) {
            pegStruct.get(i).add(numBall+1);
            double sqrt = 0;
            if (pegStruct.get(i).size() > 1) {
                sqrt = Math.sqrt(numBall+1 + pegStruct.get(i).get(pegStruct.get(i).size()-2));
            }
            if (pegStruct.get(i).size() == 1 || (pegStruct.get(i).size() > 1 && (int)sqrt*sqrt == (numBall+1+pegStruct.get(i).get(pegStruct.get(i).size()-2)))) {
                rec(numBall+1);
            }
            if (i == numPegs-1) {
                gotAnswer = true;
            }
            pegStruct.get(i).remove(pegStruct.get(i).size()-1);
        }
    }
   
    public static void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
       
        int numTests = sc.nextInt();
        for (int i = 0; i < numTests; i++) {
            numPegs = sc.nextInt();
           
            pegStruct = new HashMap<>();
            for (int j = 0; j < numPegs; j++) {
                pegStruct.put(j, new ArrayList<Integer>());
            }
           
            maxBall = 0;
            gotAnswer = false;
            pegStruct.get(0).add(1);
            rec(1);
           
            System.out.println(maxBall);
        }
                               
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução