(UVA) How do you add? - Solution

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

The solution below used Dynamic Programming to solve this problem.


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

class Main {
    public int n;
    public int k;
    public int[][] matrix;
   
    public int rec(int number, int numNumbersConsidered) {
        if (number < 0 || numNumbersConsidered < 0) {
            return 0;
        }
       
        if (numNumbersConsidered == 0) {
            if (number == 0) {
                return 1;
            }
            return 0;
        }
       
        if (matrix[number][numNumbersConsidered] != -1) {
            return matrix[number][numNumbersConsidered];
        }
       
        int sum = 0;
        for (int i = 0; i <= n; i++) {
            sum += rec(number-i, numNumbersConsidered-1);
        }
        matrix[number][numNumbersConsidered] = sum%1000000;
       
        return matrix[number][numNumbersConsidered];
    }
   
    public void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
       
        matrix = new int[101][101];
       
        n = sc.nextInt();
        k = sc.nextInt();
        while (n != 0 || k != 0) {
            for (int i = 0; i <= n; i++) {
                for (int j = 0; j <= k; j++) {
                    matrix[i][j] = -1;
                }
            }
            int count = rec(n, k);
           
            bw.write(count+"\n");
           
            n = sc.nextInt();
            k = sc.nextInt();
        }
                                      
        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) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução