- 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
- 96 lines of Java from the credited upstream file ccc07s3.java.
- The implementation visibly relies on sequence storage.
- 4 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.
1234567891011121314151617181920212223242526 27import java.awt.*;28import hsa.*;29 30public class CCC2007S3Friends31{32 static Console c;33 static int n, i, size, distance;34 static String s1, s2, x;35 static String[] friend;36 static String[] number;37 38 public static void main (String[] args)39 {40 c = new Console ();41 TextInputFile f = new TextInputFile ("s3.2.in");42 43 44 n = f.readInt ();45 friend = new String [n];46 number = new String [n];47 size = n;48 for (int i = 0 ; i < n ; i++)49 {50 s1 = f.readString ();51 s2 = f.readString ();52 number [i] = s1;53 friend [i] = s2;54 }55 56 57 58 s1 = f.readString ();59 s2 = f.readString ();60 while (!(s1.equals ("0") && s2.equals ("0")))61 {62 x = s1;63 i = find (x);64 distance = 0;65 while (i >= 0 && !(friend [i].equals (s1) || friend [i].equals (s2)))66 {67 distance++;68 x = friend [i];69 i = find (x);70 }71 if (i >= 0 && friend [i].equals (s2))72 c.println ("Yes " + distance);73 else74 c.println ("No");75 s1 = f.readString ();76 s2 = f.readString ();77 }78 }79 80 81 82 83 public static int find (String s)84 {85 int i;86 i = 0;87 while (i < size && !number [i].equals (s))88 i++;89 if (i < size)90 return i;91 else92 return -1;93 94 }95}96