(UVA) Ingenuous Cubrency - Solution

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

The solution below used the concept of Coin Change, related to Dynamic Programming, to solve this problem.


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

class Main {
    public int[] cubeCoins;
    public long[][] matrix;
   
    public long coinChange(int money, int indexCubeCoins) {
        if (money == 0) {
            return 1;
        }
        else if (money < 0 || indexCubeCoins < 1) {
            return 0;
        }
       
        if (matrix[money][indexCubeCoins] != -1) {
            return matrix[money][indexCubeCoins];
        }
       
        long use = coinChange(money-cubeCoins[indexCubeCoins], indexCubeCoins);
        long notUse = coinChange(money, indexCubeCoins-1);
        matrix[money][indexCubeCoins] = use+notUse;
        return matrix[money][indexCubeCoins];
    }
   
    public void fillCubeCoins() {
        for (int i = 1; i < 22; i++) {
            cubeCoins[i] = i*i*i;
        }
    }
   
    public void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        matrix = new long[10000][22];
        for (int i = 0; i < 10000; i++) {
            for (int j = 0; j < 22; j++) {
                matrix[i][j] = -1;
            }
        }
       
        cubeCoins = new int[22];
        fillCubeCoins();
       
        while (sc.hasNext()) {
            int number = sc.nextInt();
           
            long result = coinChange(number, 21);
       
            bw.write(result+"\n");
        }
               
        bw.flush();
        bw.close();
       
        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