- 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
- 100 lines of Java from the credited upstream file ccc05s5.java.
- The implementation visibly relies on sequence storage.
- 5 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.
1234567891011121314151617181920212223242526272829303132333435363738 39import java.awt.*;40import hsa.*;41 42public class CCC2005s5PinballRankingMerge43{44 static Console c;45 static double I;46 47 public static void main (String[] args)48 {49 c = new Console ();50 TextInputFile f = new TextInputFile ("s5.9.in");51 I = 0;52 int[] a = new int [100001];53 54 int n;55 n = f.readInt ();56 for (int x = 0 ; x < n ; x++)57 a [x] = f.readInt ();58 mergeSort (a, 0, n - 1);59 c.println ((I + n) / n, 0, 2);60 }61 62 63 64 public static void mergeSort (int[] a, int x, int z)65 {66 if (x < z)67 {68 int y = (x + z) / 2;69 mergeSort (a, x, y);70 mergeSort (a, y + 1, z);71 I += merge (a, x, y, z);72 }73 }74 75 76 public static double merge (int[] a, int x, int y, int z)77 {78 int[] newa = new int [z - x + 1];79 int xx = x;80 int yy = y + 1;81 int k = 0;82 double total = 0;83 while (xx <= y && yy <= z)84 if (a [xx] <= a [yy])85 newa [k++] = a [xx++];86 else87 {88 newa [k++] = a [yy++];89 total = total + (y + 1 - xx);90 }91 while (xx <= y)92 newa [k++] = a [xx++];93 while (yy <= z)94 newa [k++] = a [yy++];95 for (xx = x ; xx <= z ; xx++)96 a [xx] = newa [xx - x];97 return total;98 }99}100