# UVa 10664. Luggage

The UVa 10664: Luggage is a typical example of the problems that can be solved using dynamic programming (DP) technique. In fact, after further analysis, this problem can be realized as a special case of Subset-Sum problem, which we have discussed in a recent post.

The following Java code snippet outlines an algorithm using dynamic programming to solve this problem. Notice that the function `solveLuggageProblem` applies a bottom-up DP to construct `dpTable`. The `boolean` value of each `dpTable[i][j]` implies that whether it is possible to achieve weight `j` from the weights of `1..i` suitcases. In this way, it determines whether `halfWeight` — the half of the total weights (of the suitcases)– can be derived from using `1..n` suitcases, i.e., whether the weights of suitcases can be distributed equally into the boots of two cars.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 import java.io.PrintWriter; import java.util.Scanner; class Main { private final Scanner in; private final PrintWriter out; public Main(){ in = new Scanner(System.in); out = new PrintWriter(System.out, true); } public Main(Scanner in, PrintWriter out){ this.in = in; this.out = out; } private static int[] readLineAsIntegers(String input){ String [] ints = input.trim().split(" "); int [] rets = new int[ints.length]; for (int i = 0 ;i < ints.length; i++) rets[i] = Integer.parseInt(ints[i]); return rets; } private String solveLuggageProblem(int[] weights){ final String _TRUE = "YES"; final String _FALSE = "NO"; int totalWeight = getTotalWeight(weights); if (totalWeight%2 != 0) return _FALSE; int n = weights.length+1; int halfWeight = totalWeight/2; boolean [][] dpTable = new boolean [n][halfWeight+1]; // Base case 1: weights = 0 for all n --> True for(int i = 0;i False for(int i = 1;i
view raw uva10664.java hosted with ❤ by GitHub