- 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
- 124 lines of Java from the credited upstream file ccc03s5.java.
- The implementation visibly relies on sequence storage.
- 6 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.
1234567 891011 121314151617 181920 2122 23import java.awt.*;24import hsa.*;25 26public class S5TruckingPrims27{28 static Console cc;29 static int [] [] weights;30 static int [] dest;31 32 static int n, r, d, a, b, c, tt;33 34 static int [] val;35 static boolean [] visited;36 static int max, maxt, k, smallest;37 38 39 public static void main (String [] args)40 {41 cc = new Console ();42 43 44 TextInputFile fi = new TextInputFile ("truck5.in");45 TextOutputFile fo = new TextOutputFile ("truck5a.out");46 47 n = fi.readInt ();48 r = fi.readInt ();49 d = fi.readInt ();50 51 weights = new int [n + 1] [n + 1];52 dest = new int [d];53 54 55 56 for (int i = 0 ; i < r ; i++)57 {58 a = fi.readInt ();59 b = fi.readInt ();60 c = fi.readInt ();61 if (a > b)62 {63 tt = a;64 a = b;65 b = tt;66 }67 if (c > weights [a] [b])68 {69 weights [a] [b] = c;70 weights [b] [a] = c;71 }72 }73 74 75 for (int i = 0 ; i < d ; i++)76 dest [i] = fi.readInt ();77 78 79 val = new int [n + 1];80 visited = new boolean [n + 1];81 for (k = 0 ; k < n + 1 ; k++)82 {83 val [k] = 0;84 visited [k] = false;85 }86 87 val [1] = 100000;88 maxt = 1;89 90 do91 {92 k = maxt;93 visited [maxt] = true;94 max = 0;95 maxt = -1;96 for (int t = 1 ; t < n + 1 ; t++)97 {98 if (val [t] < Math.min (val [k], weights [k] [t]))99 val [t] = Math.min (val [k], weights [k] [t]);100 if (val [t] >= max && !visited [t])101 {102 max = val [t];103 maxt = t;104 }105 }106 }107 while (maxt != -1);108 109 110 smallest = 100000;111 for (int i = 0 ; i < d ; i++)112 if (val [dest [i]] < smallest)113 smallest = val [dest [i]];114 115 fo.println (smallest);116 cc.println (smallest);117 118 fi.close ();119 fo.close ();120 }121}122 123 124