- 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
- 133 lines of Java from the credited upstream file ccc00s3.java.
- The implementation visibly relies on sequence storage.
- 12 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.
1234567891011121314 151617 18 19import java.awt.*;20import hsa.*;21 22public class J5Surfin23{24 static Console c; 25 public static String [] url = new String [100];26 27 28 public static void main (String [] args)29 {30 c = new Console ();31 boolean [] [] adj = new boolean [100] [100];32 String line, to, a, b;33 int n, x, y, k;34 35 TextInputFile fi = new TextInputFile ("surf.in2");36 TextOutputFile fo = new TextOutputFile ("surf.ou2");37 38 for (int i = 0 ; i < 100 ; i++)39 for (int j = 0 ; j < 100 ; j++)40 {41 if (i == j)42 adj [i] [j] = true;43 else44 adj [i] [j] = false;45 }46 47 48 n = fi.readInt ();49 for (int i = 0 ; i < n ; i++)50 {51 url [i] = fi.readLine ();52 line = fi.readLine ();53 while (!line.equals ("</HTML>"))54 line = fi.readLine ();55 }56 fi.close ();57 58 59 fi = new TextInputFile ("surf.in2");60 for (int i = 0 ; i < n ; i++)61 {62 line = fi.readLine ();63 line = fi.readLine ();64 while (!line.equals ("</HTML>"))65 {66 x = line.indexOf ("<A HREF=\"");67 while (x >= 0)68 {69 y = line.indexOf ("\">", x + 9);70 to = line.substring (x + 9, y);71 fo.println ("Link from " + url [i] + " to " + to);72 c.println ("Link from " + url [i] + " to " + to);73 k = find (to, n);74 adj [i] [k] = true;75 line = line.substring (y + 2);76 x = line.indexOf ("<A HREF=\"");77 }78 line = fi.readLine ();79 }80 }81 82 83 warshalls (adj);84 85 86 a = fi.readLine ();87 fo.println ();88 c.println ();89 while (!a.equals ("The End"))90 {91 b = fi.readLine ();92 if (adj [find (a, n)] [find (b, n)])93 {94 fo.println ("Can surf from " + a + " to " + b);95 c.println ("Can surf from " + a + " to " + b);96 }97 else98 {99 fo.println ("Can't surf from " + a + " to " + b);100 c.println ("Can't surf from " + a + " to " + b);101 }102 a = fi.readLine ();103 }104 fi.close ();105 fo.close ();106 }107 108 109 110 111 static public int find (String s, int n)112 {113 int k = 0;114 while (k < n && !url [k].equals (s))115 k++;116 if (k == n)117 c.println ("Error: can't find " + s);118 return k;119 }120 121 122 123 static public void warshalls (boolean [] [] a)124 {125 for (int y = 0 ; y < 100 ; y++)126 for (int x = 0 ; x < 100 ; x++)127 if (a [x] [y])128 for (int j = 0 ; j < 100 ; j++)129 if (a [y] [j])130 a [x] [j] = true;131 }132}133