Approach
Depth-first search
For CCC 2009 S4 - Ship and Shop, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 107 lines of Java from the credited upstream file ccc09s4.java.
- The implementation visibly relies on sequence storage.
- 7 loop blocks detected.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123456789101112131415 16import java.awt.*;17import hsa.*;18 19public class CCC2009S4ShipAndShop20{21 22 public static int[] [] ship; 23 public static int[] shop;24 public static boolean[] visited;25 public static boolean improvement;26 public static int n, d;27 public static Console c;28 29 public static void main (String[] args)30 {31 32 c = new Console ();33 TextInputFile f = new TextInputFile ("s4.5.in");34 35 n = f.readInt ();36 ship = new int [n + 1] [];37 shop = new int [n + 1];38 visited = new boolean [n + 1];39 for (int i = 1 ; i <= n ; i++)40 {41 ship [i] = new int [i + 1];42 shop [i] = 999999999;43 visited [i] = false;44 for (int j = 1 ; j < i ; j++)45 ship [i] [j] = 999999999;46 ship [i] [i] = 0;47 }48 49 int t = f.readInt ();50 int i, j, x;51 for (int k = 0 ; k < t ; k++)52 {53 i = f.readInt ();54 j = f.readInt ();55 x = f.readInt ();56 if (i < j && j <= n)57 ship [j] [i] = x;58 else if (j < i && i <= n)59 ship [i] [j] = x;60 }61 int k = f.readInt ();62 for (i = 0 ; i < k ; i++)63 {64 j = f.readInt ();65 x = f.readInt ();66 if (j <= n)67 shop [j] = x;68 }69 d = f.readInt ();70 c.println ("Input finished.");71 72 73 74 75 76 int old = 0;77 x = cheapest(d);78 while (x != old)79 {80 old = x;81 for (i = 1 ; i <= n ; i++)82 visited [i] = false;83 x = cheapest (d);84 }85 c.println (x);86 }87 88 89 90 91 92 public static int cheapest (int x)93 {94 if (visited [x])95 return shop [x];96 visited [x] = true;97 int smallest = shop [x];98 for (int i = 1 ; i <= n ; i++)99 if (ship [Math.max (i, x)] [Math.min (i, x)] + cheapest (i) < smallest)100 smallest = ship [Math.max (i, x)] [Math.min (i, x)] + cheapest (i);101 shop [x] = smallest;102 return smallest;103 }104}105 106 107