You are suggested to use the teaching servers burrow.soic.indiana.edu or hulk.soic.indiana.edu or tank.soic.indiana.edu for practicing C programs.
LCS(p, q) { if p==-1 or q ==-1 // base case return 0 if s1[p] == s2[q] // match case return 1 + LCS(p-1, q-1) else return MAX( LCS(p-1, q), LCS(p, q-1) ) }
Initialize full CACHE[][] with -1 LCS(p, q) { if p==-1 or q ==-1 // base case return 0 if CACHE[p][q] not equal -1 // this subproblem is already solved, return the cached value from here return CACHE[p][q] if s1[p] == s2[q] // match case return CACHE[p][q] = 1 + LCS(p-1, q-1) else return CACHE[p][q] = MAX( LCS(p-1, q), LCS(p, q-1) ) }
Initialize full CACHE[][] with -1 Initialize full Direction[][] with -1 LCS(p, q) { if p==-1 or q ==-1 // base case return 0 if CACHE[p][q] not equal -1 // this subproblem is already solved, return the cached value from here return CACHE[p][q] if s1[p] == s2[q] // match case Direction[p][q] = MATCH_CASE return CACHE[p][q] = 1 + LCS(p-1, q-1) else v1 = LCS(p-1, q) v2 = LCS(p, q-1) if v1 > v2 // decrease s1 case Direction[p][q] = DECREASE_FIRST_STRING CACHE[p][q] = v1 else // decrease s2 case Direction[p][q] = DECREASE_SECOND_STRING CACHE[p][q] = v2 return CACHE[p][q] }After all the marking of direction done, we can print the LCS with calling PrintPath(m, n):
PrintPath(p, q) { if Direction[p][q] == MATCH_CASE PrintPath(p-1, q-1) print(s1[p]) // or print(s2[q]) they are same elseif Direction[p][q] == DECREASE_FIRST_STRING PrintPath(p-1, q) elseif Direction[p][q] == DECREASE_SECOND_STRING PrintPath(p, q-1) }