Approach
Depth-first search
For CCC 2001 S5 - Post's Correspondence, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 118 lines of Java from the credited upstream file ccc01s5.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 456789 1011 12131415 1617 18import java.awt.*;19import hsa.*;20 21public class S5Post22{23 static Console c;24 static String [] a, b;25 static int m, n, k;26 static int [] iarray;27 28 public static void main (String [] args)29 {30 c = new Console ();31 32 a = new String [40];33 b = new String [40];34 iarray = new int [40];35 36 TextInputFile fi = new TextInputFile ("post3.in");37 TextOutputFile fo = new TextOutputFile ("post3.out");38 39 40 m = fi.readInt ();41 n = fi.readInt ();42 for (int i = 0 ; i < n ; i++)43 a [i] = fi.readString ();44 for (int i = 0 ; i < n ; i++)45 b [i] = fi.readString ();46 47 48 49 50 if (Post ("", "", 0))51 {52 c.println (k + 1);53 for (int f = 0 ; f <= k ; f++)54 c.println (iarray [f] + 1);55 }56 else57 c.println ("No solution.");58 }59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 static boolean Post (String ta, String tb, int p)76 {77 boolean okay;78 if (p > m)79 return false;80 else if (ta.equals (tb) && p > 0)81 return true;82 else if (!equalSoFar (ta, tb))83 return false;84 else85 {86 int i = 0;87 boolean done = false;88 while (i < n && !done)89 {90 k = p;91 iarray [k] = i;92 done = Post (ta + a [i], tb + b [i], p + 1);93 i++;94 }95 return done;96 }97 }98 99 100 101 102 103 static boolean equalSoFar (String a, String b)104 {105 if (a.equals (b))106 return true;107 else if (a.length () < b.length ())108 return b.startsWith (a);109 else if (a.length () > b.length ())110 return a.startsWith (b);111 else112 return false;113 }114}115 116 117 118