- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 131 lines of Java from the credited upstream file ccc07s5.java.
- The implementation visibly relies on sequence storage, cached states.
- 10 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123456789101112131415161718192021222324252627282930313233 3435363738 39404142434445464748495051525354555657 58 59import hsa.*;60 61public class CCC2007S5BowlingForNumbersDP62{63 static Console c;64 65 public static void main (String[] args)66 {67 int numberPins, numberBalls, width, s;68 int[] pin;69 int[] sum;70 int[] [] dp;71 72 c = new Console ();73 TextInputFile f = new TextInputFile ("s5.4.in");74 75 int tests = f.readInt ();76 for (int t = 0 ; t < tests ; t++)77 {78 79 80 numberPins = f.readInt ();81 numberBalls = f.readInt ();82 width = f.readInt ();83 pin = new int [numberPins];84 for (int i = 0 ; i < numberPins ; i++)85 pin [i] = f.readInt ();86 87 88 89 90 sum = new int [numberPins];91 s = 0;92 for (int i = 0 ; i < width ; i++)93 s += pin [i];94 sum [0] = s;95 for (int i = 1 ; i < numberPins - width + 1 ; i++)96 {97 s = s - pin [i - 1] + pin [i + width - 1];98 sum [i] = s;99 }100 for (int i = numberPins - width + 1 ; i < numberPins ; i++)101 {102 s = s - pin [i - 1];103 sum [i] = s;104 }105 106 107 dp = new int [numberBalls + 1] [numberPins];108 for (int j = 1 ; j < numberPins ; j++)109 dp [0] [j] = 0;110 for (int i = 1 ; i <= numberBalls ; i++)111 for (int j = 1 ; j < numberPins ; j++)112 dp [i] [j] = -1;113 114 115 for (int ball = 1 ; ball <= numberBalls ; ball++)116 for (int i = numberPins - 1 ; i >= 0 ; i--)117 {118 if (i >= numberPins - width)119 dp [ball] [i] = sum [i];120 else121 dp [ball] [i] = Math.max (dp [ball - 1] [i + width] + sum [i],122 dp [ball] [i + 1]);123 }124 c.println (dp [numberBalls] [0]);125 }126 }127}128 129 130 131