- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 98 lines of Java from the credited upstream file ccc00s4.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4567 89 101112 13141516 171819202122232425262728293031 323334 35import java.awt.*;36import hsa.*;37 38 39public class S4Golf40{41 static Console c;42 43 public static void main (String [] args)44 {45 c = new Console ();46 int club [] = new int [32];47 int dis, n, ans;48 49 TextInputFile fi = new TextInputFile ("golf.in1");50 TextOutputFile fo = new TextOutputFile ("golf.ou1");51 52 dis = fi.readInt ();53 n = fi.readInt ();54 for (int i = 0 ; i < n ; i++)55 club [i] = fi.readInt ();56 ans = solve (dis, club, n);57 if (ans == -1)58 {59 fo.println ("Roberta acknowledges defeat.");60 c.println ("Roberta acknowledges defeat.");61 }62 else63 {64 fo.println ("Roberta wins in " + ans + " strokes.");65 c.println ("Roberta wins in " + ans + " strokes.");66 }67 }68 69 70 public static int solve (int distance, int [] club, int n)71 {72 int [] f;73 int min, t;74 75 f = new int [distance + 1];76 77 f [0] = 0;78 79 for (int x = 1 ; x <= distance ; x++)80 {81 min = 999999999;82 for (int j = 0 ; j < n ; j++)83 {84 t = x - club [j];85 if (t >= 0 && f [t] >= 0 && f [t] < min)86 min = f [t];87 }88 if (min < 999999999)89 f [x] = min + 1;90 else91 f [x] = -1;92 }93 return f [distance];94 }95}96 97 98