- 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
- 140 lines of Java from the credited upstream file ccc08s4.java.
- The implementation visibly relies on sequence storage.
- 10 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.
12345678910111213141516171819202122232425262728293031323334353637 38 39import java.awt.*;40import hsa.*;41 42public class CCC2008S4TwentyFour43{44 static Console c;45 46 47 48 49 50 static int doOperations (int[] hand, int handSize, int[] [] newHand, int k)51 {52 for (int i = 0 ; i < handSize ; i++)53 for (int j = 0 ; j < handSize ; j++)54 if (i != j)55 {56 57 newHand [k] [0] = hand [i] + hand [j];58 59 int q = 1;60 for (int p = 0 ; p < handSize ; p++)61 if (!(p == i || p == j))62 newHand [k] [q++] = hand [p];63 k++;64 65 66 newHand [k] [0] = hand [i] - hand [j];67 68 q = 1;69 for (int p = 0 ; p < handSize ; p++)70 if (!(p == i || p == j))71 newHand [k] [q++] = hand [p];72 k++;73 74 75 newHand [k] [0] = hand [i] * hand [j];76 77 q = 1;78 for (int p = 0 ; p < handSize ; p++)79 if (!(p == i || p == j))80 newHand [k] [q++] = hand [p];81 k++;82 83 84 if (hand [j] != 0 && hand [i] % hand [j] == 0)85 {86 newHand [k] [0] = hand [i] / hand [j];87 88 q = 1;89 for (int p = 0 ; p < handSize ; p++)90 if (!(p == i || p == j))91 newHand [k] [q++] = hand [p];92 k++;93 }94 }95 return k;96 }97 98 99 public static void main (String[] args)100 {101 int n, size, newSize;102 int[] [] hand, newHand;103 c = new Console ();104 TextInputFile f = new TextInputFile ("s4.5.in");105 n = f.readInt ();106 for (int i = 0 ; i < n ; i++)107 {108 newHand = new int [1] [4];109 newHand [0] [0] = f.readInt ();110 newHand [0] [1] = f.readInt ();111 newHand [0] [2] = f.readInt ();112 newHand [0] [3] = f.readInt ();113 newSize = 1;114 115 116 for (int k = 4 ; k > 1 ; k--)117 {118 size = newSize;119 hand = newHand;120 newHand = new int [10000] [3];121 newSize = 0;122 for (int j = 0 ; j < size ; j++)123 newSize = doOperations (hand [j], k, newHand, newSize);124 }125 126 127 size = newSize;128 int biggest = 0;129 for (int j = 0 ; j < size && biggest < 24 ; j++)130 if (newHand [j] [0] > biggest && newHand [j] [0] <= 24)131 biggest = newHand [j] [0];132 c.println (biggest);133 }134 135 }136}137 138 139 140